Java 为什么可以';我调用一个带有实现接口的枚举列表的方法吗?
我试图调用一个方法,该方法使用一个带有枚举列表的接口列表(实现接口)。这会产生以下编译错误:Java 为什么可以';我调用一个带有实现接口的枚举列表的方法吗?,java,generics,enums,Java,Generics,Enums,我试图调用一个方法,该方法使用一个带有枚举列表的接口列表(实现接口)。这会产生以下编译错误: The method method(List<Interface>) in the type Class is not applicable for the arguments (List<Enum>) 这是实现接口的枚举: public interface Interface { } public enum Enum implements Interface { } 这是
The method method(List<Interface>) in the type Class is not applicable for the arguments (List<Enum>)
这是实现接口的枚举:
public interface Interface {
}
public enum Enum implements Interface {
}
这是调用类:
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.
}
}
import java.util.ArrayList;
导入java.util.List;
公共课{
公共静态无效方法(列表){
}
公共静态void main(字符串[]args){
List enumList=new ArrayList();
方法(enumList);//此行给出编译错误。
}
}
为什么会有编译错误?在我看来,它应该可以工作,因为Enum实现了该接口。公共静态无效方法(List因为List
是-not-aList
)
public static void method(List<? extends Interface> list){
}
您应该将变量更改为List
,或者将方法签名更改为takeList这是因为即使是Car
扩展Vehicle
,List
不扩展List
。如果是,您可以执行以下操作:
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.
listOfCars=newarraylist();
车辆列表=车辆列表;
车辆列表。添加(新自行车());
//现在汽车清单上有一辆自行车:不漂亮。
尽管Enum实现了接口,但List不是List的子类型。
如果将方法签名修改为以下内容,则可以使用
method(List<? extends Interface> list)
方法(列出Yes的可能重复项,这是一个重复项。我在前面查看时找不到该重复项。请注意,您可以对数组执行相同的操作(导致ArrayStoreException),并且无法修复该问题以保持兼容性。