gpt4 book ai didi

java - Java 中的泛型和参数化类型

转载 作者:搜寻专家 更新时间:2023-11-01 01:35:33 24 4
gpt4 key购买 nike

下面的代码会导致编译时错误:

The method add(capture#1-of ? extends Object) in the type List is not applicable for the arguments (String)

代码:

List<? extends Object> a1 = new ArrayList();
a1.add("string");

错误在行:

a1.add("string");

既然 String 类继承自 Object,为什么 ref a1 不接受 String 类型?

最佳答案

我推荐阅读这篇文章,http://java.dzone.com/articles/covariance-and-contravariance . (斜体添加是我的)

In summary, we use covariance <? extends Object> when we only intend to take generic values out of a structure. We use contravariance <? super Object> when we only intend to put generic values into a structure and we use an invariant <Object> when we intend to do both.

您将列表定义为包含协变对象类型,这意味着您可以编写 Object o = a1.get(1)但你不能写 a1.add("foo") .如果您希望能够添加对象但不能取回它们,那么您需要像这样定义您的列表:

List<? super Object> a1 = new ArrayList<>();

有点不幸,在我看来,语言作者使用了术语 extendsuper表示协变和逆变,特别是在上面的例子中,因为没有 Object 的父类(super class)型.

关于java - Java 中的泛型和参数化类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16251906/

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