为什么我不能使用实现接口的枚举列表调用方法?
我正在尝试调用一个方法,该方法采用带有枚举列表(实现接口)的接口列表。这会给出以下编译错误:
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 实现了该接口。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是因为即使
Car
扩展Vehicle
,List
也不扩展List;
。如果是这样,您可以执行以下操作:This is because even is
Car
extendsVehicle
,List<Car>
does not extendList<Vehicle>
. If it did, you could do the following:因为
List
不是List
。您应该将变量更改为
List
,或者更改方法签名以采用List
Because
List<Enum>
is-not-aList<Interface>
.You should either change the variable to
List<Interface>
, or change the method signature to takeList<? extends Interface>
虽然 Enum 实现了 Interface,但 List<枚举>不是 List < 的子类型界面>.
如果将方法签名修改为以下将起作用。
有关更多详细信息,请参阅文档
http://download.oracle.com/javase/tutorial/java/generics /通配符.html
Though the Enum implements the Interface, List< Enum > is not subtype of List < Interface >.
If you modify the method signature to following will work.
For further details go through the documentation
http://download.oracle.com/javase/tutorial/java/generics/wildcards.html