2011-08-02 4 views
0

인터페이스를 구현하는 Enum 목록을 사용하여 Interface 목록을 취하는 메서드를 호출하려고합니다.인터페이스를 구현하는 enum 목록이있는 메소드를 호출 할 수없는 이유는 무엇입니까?

public enum Enum implements Interface { 
} 

이 호출하는 클래스는 다음과 같습니다 :

이 인터페이스를 구현하는 열거입니다

public interface Interface { 
} 

:이 인터페이스

The method method(List<Interface>) in the type Class is not applicable for the arguments (List<Enum>) 

이 다음과 같은 컴파일 오류가 있습니다

import java.util.ArrayList; 
import java.util.List; 

public class Class { 
    public static void method(List<Interface> list){ 
    } 

    public static void main(String[] args) { 
     List <Enum> enumList = new ArrayList<Enum>(); 
     method(enumList); //This line gives the compile error. 
    } 
} 

컴파일 오류가 발생하는 이유는 무엇입니까? 나에게 그것은 Enum이 그 인터페이스를 구현하기 때문에 작동 할 것으로 보인다.

+2

[자바 제네릭 (http://stackoverflow.com/questions/1794842/generics-in-java)의 중복 가능성 – Thilo

+0

네, 중복입니다. 내가 더 일찍 찾고 있었을 때 나는 그것을 발견 할 수 없었다. –

답변

1

취할 방법 서명을 변경해야 하나. 이 그랬다면, 당신은 다음 작업을 수행 할 수 있습니다 :

List<Car> listOfCars = new ArrayList<Car>(); 
List<Vehicle> listOfVehicles = listOfCars; 
listOfVehicles.add(new Bicycle()); 
// and now the list of cars contains a bicycle: not pretty. 
+0

배열 (ArrayStoreException의 결과)에서 동일한 작업을 수행 할 수 있으며 호환성을 유지하기 위해 수정할 수 없다는 것에 유의하십시오. – Thilo

5
public static void method(List<? extends Interface> list){ 
} 
1

List<Enum>이 때문에 IS-하지-A List<Interface>.

당신은 하지List<Vehicle>을 확장 List<Car>는 않습니다, List<Interface>에 변수를 변경하거나 심지어 CarVehicle를 확장하기 때문이다 List<? extends Interface>

1

을 열거이 인터페이스를 구현하지만, 목록 < 열거는>> 목록 < 인터페이스의 하위 유형이 아닙니다. 메소드 서명을 다음과 같이 수정하면 작동합니다. 자세한 내용은

method(List<? extends Interface> list) 

는 문서를 통해 이동 http://download.oracle.com/javase/tutorial/java/generics/wildcards.html

관련 문제