我正在使用下面的代码并尝试添加 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{
}
我想知道为什么编译器会在这里抛出错误?
最佳答案
如果您浏览Generic Guidelines Oracle 文档指出,此类列表声明往往是只读(无法执行写入操作)
引自页面
A list defined by
List<? extends ...>
can be informally thought of as read-only, but that is not a strict guarantee.
根据您的示例,让我们假设 Child2
和Child3
extends Parent
,那么
List<? extends Parent>
list 可以是任何这些子类的列表。添加特定的子类元素可能会导致运行时错误,因此编译器会提前提示
关于通配符扩展的 Java 通用类型仅允许添加 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25619676/