gpt4 book ai didi

java - 带有扩展的泛型

转载 作者:行者123 更新时间:2023-12-01 15:28:44 24 4
gpt4 key购买 nike

在:

public class Organic<E> {
void react(E e) {
}

static void main(String[] args) {
Organic<? extends Elem> compound = new Organic<Elem>();
compound.react(new Elem());
}
}

class Elem {}

为什么会出现以下编译错误?

The method react(capture#1-of ? extends Elem) in the type Organic<capture#1-of ? extends Elem> is not applicable for the arguments (Elem)

最佳答案

来自http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

List 是有界通配符的示例。这 ?代表未知类型,就像我们之前看到的通配符一样。然而,在这种情况下,我们知道这个未知类型实际上是 Shape 的子类型。 (注意:它可以是 Shape 本身,也可以是某个子类;它不需要从字面上扩展 Shape。)我们说 Shape 是通配符的上限。

像往常一样,使用通配符的灵 active 是要付出代价的。这个代价是现在在方法主体中写入形状是非法的。例如,这是不允许的:

public void addRectangle(List<? extends Shape> shapes) {
// Compile-time error!
shapes.add(0, new Rectangle());
}

您应该能够弄清楚为什么上面的代码被禁止。 Shapes.add() 的第二个参数的类型是 ?扩展 Shape——Shape 的一个未知子类型。因为我们不知道它是什么类型,所以我们不知道它是否是 Rectangle 的父类(super class)型;它可能是也可能不是这样的父类(super class)型,因此在那里传递 Rectangle 是不安全的。

具体来说你的解决方案,你不能用Elem的对象调用react。类型,与类型 Organic<? extends Elem> 一样您可以合法分配 compound = new Organic<ElemSubClass>() - 然后react会导致编译错误,因为你不能调用它传递一个父类(super class)对象。

关于java - 带有扩展的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9838460/

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