为什么我不能调用一个实现一个接口的枚举列表的方法?

编程入门 行业动态 更新时间:2024-10-21 16:32:47
本文介绍了为什么我不能调用一个实现一个接口的枚举列表的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在尝试调用一个方法,该方法使用一个列表的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.

更多推荐

为什么我不能调用一个实现一个接口的枚举列表的方法?

本文发布于:2023-10-31 06:07:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545239.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   方法   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!