我正在使用下面的代码并尝试添加 CHild 对象是列表:
List<? extends Parent> list = new ArrayList<Child>();
list.add(new Child()); //error: The method add(capture#1-of ? extends Parent) in the type List<capture#1-of ? extends Parent> is not applicable for the arguments (Child)
class Parent{
}
class Child extends Parent{
}
我想知道为什么编译器会在这里抛出错误?
如果您经过通用指南 http://docs.oracle.com/javase/tutorial/java/generics/wildcardGuidelines.htmlOracle 文档指出,此类列表声明往往是只读(不能执行写操作)
引用自页面
定义的列表List<? extends ...>
可以非正式地认为是
只读,但这并不是严格的保证。
根据你的例子,让我们假设Child2
and Child3
extends Parent
, then
List<? extends Parent>
list 可以是任何这些子类的列表。添加特定的子类元素可能会导致运行时错误,因此编译器会提前抱怨
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)