通配符扩展的 Java 通用类型仅允许添加 null

标签 java generics compiler-errors wildcard extends

我正在使用下面的代码并尝试添加 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.

根据您的示例,让我们假设 Child2Child3 extends Parent ,那么

List<? extends Parent> list 可以是任何这些子类的列表。添加特定的子类元素可能会导致运行时错误,因此编译器会提前提示

关于通配符扩展的 Java 通用类型仅允许添加 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25619676/

相关文章:

Swift Vapor 示例未编译

java - Windows Logo (TM) 认证的应用程序是否更难用 Java 编写?

c# - 从通用存储库返回动态列表

android - 在 active-android 中发现意外的元数据类型

Java:泛型和未经检查的——为什么?

java - 泛型和方法

python - 无法导入csv文件进行协作?

java - 在我的游戏中实现 ActionListener 第 2 部分

java - 请解释一下下面的代码

java - GWT DataGrid 中可扩展行的简单示例