gpt4 book ai didi

java泛型和通配符

转载 作者:行者123 更新时间:2023-11-30 06:34:09 26 4
gpt4 key购买 nike

在 java generic 中,我理解通配符、super 和 extends 的含义,但不明白为什么不允许我添加任何东西,以及为什么允许我在层次结构中添加 upto SomeType,但在层次结构?

class Animal {}
class Cat extends Animal{}

以下方法可以获取 Animal 列表或 Animal 的子列表,即 Cat,但除此之外别无其他并且不允许我添加任何内容,如果尝试添加,编译器会阻止我,为什么?

void addAminal(List<? extends Aminal> aList){
aList.add(new Cat()); // compiler error
aList.add(new Animal()); // compiler error
}

现在下面的方法可以接受 Animal 的任何列表或 Animal 的任何父类(super class)型,但不能接受 Animal 的子类型,并且我可以将对象添加到 Animal 或层次结构中更低的对象,所以当我尝试添加 Object 时,编译器会提示为什么?

void addAnimal(List<? super Animal> aList){
aList.add(new Animal()); // no error
aList.add(new Cat()); // no error
aList.add(new Object()); // compiler error why ?
}

谢谢艾莉亚

最佳答案

假设您定义了一个新类:

class Tabby extends Cat {}

然后您执行了以下操作:

List<Tabby> aList = new ArrayList<Tabby>();
addAnimal(aList);

毫不奇怪,这个列表不应该有 Animal 甚至不是 Tabby 的 Cat,但如果编译器没有标记错误,那将是你所拥有的。

原因是您已指定 addAnimal 获取扩展 Animal 的列表,但该列表可能具有高度限制性。然而,这将编译:

void addAnimal(List<Animal> aList){
aList.add(new Cat()); // OK
aList.add(new Animal()); // OK
}

使用 super 也可以,因为 CatAnimal 的实例是 的任何父类(super class)的实例动物

关于java泛型和通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7344330/

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