Java通配符的通用类型扩展允许仅添加null [英] Java Generic Type for Wildcard extends allow to add only null
问题描述
我正在使用以下代码,并尝试添加CHild对象作为列表:
I am using the below code and tryin to add CHild object is the list:
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{
}
我想知道为什么编译器在这里抛出错误?
I want to know why compiler throws error here?
推荐答案
如果您遵循Oracle所述的通用准则 docs,这类列表声明通常是只读(无法执行写操作)
If you go through the Generic Guidelines stated by Oracle docs, these kind of list declarations are tend to be read-only (no write operations can be performed)
从页面引用
由
List< ;?扩展...>
可以被非正式地认为是
只读,但这并不是严格的保证。
A list defined by
List<? extends ...>
can be informally thought of as read-only, but that is not a strict guarantee.
根据您的示例,让我们假设 Child2
和 Child3
扩展父项
,然后
As per your example, let us assume Child2
and Child3
extends Parent
, then
列表< ;? extends Parent>
list可以是任何这些子类的列表。添加特定的子类元素可能会导致运行时错误,因此编译器会提前抱怨
List<? extends Parent>
list can be a list of any of these subclasses. Adding a specific subclass element can cause runtime error, thus compiler complains in advance
这篇关于Java通配符的通用类型扩展允许仅添加null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!