gpt4 book ai didi

java - 如何使java列表协变

转载 作者:行者123 更新时间:2023-11-29 08:05:37 25 4
gpt4 key购买 nike

我有以下类(class)

public class Animal


public class Dog extends Animal


public class Cat extends Animal

为了测试,我有一个驱动程序类。

public class Driver {
public static void main(String[] args){
List<? extends Animal> animalList = Arrays.<Dog>asList(new Dog(), new Dog(), new Dog());
animalList.add(new Dog()) // Compilation error
}
}

默认情况下,列表是不变类型的容器。例如说我们有 List<Object> objectList , ArrayList<String> stringList我们不能将 stringList 替换为 objList。这将导致编译错误

我的尝试是使列表像在 Driver 类中一样具有协变性。

根据<? extends Animal>我们可以应用任何属于 Animal 子类型的对象,包括 Animal 类型。

但是我在指示的行中遇到了编译问题。有人可以从理论上解释我哪里出错了。

最佳答案

我认为您误解了通用通配符 (?)。来自Java tutorial on the subject :

There is, as usual, a price to be paid for the flexibility of using wildcards. That price is that it is now illegal to write into shapes in the body of the method. For instance, this is not allowed:

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

You should be able to figure out why the code above is disallowed. The type of the second parameter to shapes.add() is ? extends Shape -- an unknown subtype of Shape. Since we don't know what type it is, we don't know if it is a supertype of Rectangle; it might or might not be such a supertype, so it isn't safe to pass a Rectangle there.

Java 泛型集合不是协变的;参见例如Java theory and practice: Generics gotchas寻求解释。

关于java - 如何使java列表协变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11484400/

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