我有一个 List<? extends MyClass> list
我想将其类扩展到 MyClass
的对象添加到此列表中和对象是 MyClass
的实例:
list.add(new ClassThatExtendsMyClass());
list.add(new MyClass());
但是 eclipse 显示构建错误:
The method add(capture#9-of ? extends MyClass) in the type List is not applicable for the arguments (MyClass)
我该如何解决这个问题?
最佳答案
泛型引用中的 Java 关键字 extends 用于限制实际的泛型实现与命名类型不低于派生。特别是它可以是一个子类。如果类型用于提取值并对其进行操作,则应使用它。然后使用基类的接口(interface)而不涉及该类的实际类型(实现/实现)。
当你有一个特定的类并需要传递(放入)集合或其他通用类对象时,指向该对象的引用应该有super 关键字,它限制实际对象不比命名类型派生。
下面的代码示例。假设我们有类 Base
和 Derived
,其中 Derived extends Base
,类 Base
有一个接口(interface)方法 foo()
并且都有默认构造函数。
void service() {
List<Base> theList = new ArrayList<Base>();
produceObjects(theList);
consumeObjects(theList);
}
void produceObjects(List<? super Base> consumerList) {
consumerList.add(new Derived());
}
void consumeObjects(List<? extends Base> producerList) {
for (Base base : producerList) {
base.foo();
}
}
关于java - 将 BaseClass 实例插入 List<?扩展基类> (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26303692/