为什么不能调用带有实现接口的枚举列表的方法? [英] Why can't I call a method with a list of enum which implement an interface?
本文介绍了为什么不能调用带有实现接口的枚举列表的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试调用一个方法,该方法采用一个接口列表和一个枚举列表(实现接口).这将产生以下编译错误:
I am trying to call a method which takes a list of Interface with a list of Enum (which implements Interface). This gives the following compile error:
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.
}
}
为什么会出现编译错误?在我看来,这应该起作用,因为Enum实现了该接口.
Why is there a compile error? To me it seems that it should work because the Enum implements that interface.
推荐答案
这是因为即使 Car
扩展了 Vehicle
, List< Car>
不扩展 List< Vehicle>
.如果这样做,则可以执行以下操作:
This is because even is Car
extends Vehicle
, List<Car>
does not extend List<Vehicle>
. If it did, you could do the following:
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.
这篇关于为什么不能调用带有实现接口的枚举列表的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文