本文介绍了为什么我不能调用一个实现一个接口的枚举列表的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试调用一个方法,该方法使用一个列表的Enum(实现Interface)的接口列表。这给出以下编译错误: 类型类中的方法方法(List< Interface>)不适用于参数(列表<枚举>)
这是界面:
public interface Interface {}这是实现接口的枚举:
public enum Enum implements Interface {}这是调用类:
code> import java.util.ArrayList; import java.util.List; public class Class { public static void method(List< Interface> list){} public static void main(String [] args ){列表<枚举> enumList = new ArrayList&Enum>(); 方法(枚举列表); //这行给出编译错误。 } }为什么有编译错误?对我来说似乎应该有效,因为枚举实现了这个接口。
解决方案这是因为即使是汽车延伸车辆,列表< Car> 不延伸列表<车辆> 。如果这样做,您可以执行以下操作:
列表< Car> listOfCars = new ArrayList< Car>(); 列表<车辆> listOfVehicles = listOfCars; listOfVehicles.add(new Bicycle()); //现在汽车列表包含一辆自行车:不漂亮。
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>)This is the interface:
public interface Interface { }This is the enum that implements the interface:
public enum Enum implements Interface { }This is the calling class:
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. } }Why is there a compile error? To me it seems that it should work because the Enum implements that interface.
解决方案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.
更多推荐
为什么我不能调用一个实现一个接口的枚举列表的方法?
发布评论