gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:20:51 25 4
gpt4 key购买 nike

我正在使用下面的代码并尝试添加 CChild 对象是列表:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com