gpt4 book ai didi

java - Collection 意味着?

转载 作者:行者123 更新时间:2023-12-03 19:22:03 27 4
gpt4 key购买 nike

为什么它在第 23 行抛出编译错误。'a' 是 Apple 类的对象,col 是包含 Apple 对象的列表,但它仍然是抛出下面提到的编译错误:

类型 Collection 中的方法 add(capture#1-of ? extends Fruit) 不适用于参数 (Fruit)

public class Basket {
List<Fruit> list;
public Basket() {
list = new ArrayList<>();
}
public Basket(List<Fruit> plist) {
list = plist;
}

void addFruit(Collection<? extends Fruit> col) { // this does not work
// void addFruit(Collection<Fruit> col) { // this works
Fruit a = new Apple();
Apple a1 = new Apple();
Fruit f1 = new Fruit();
col.add(a);// line 23
}

int getSize() {
return list.size();
}

public static void main(String[] args) {
Fruit f1 = new Apple();
Fruit f2 = new Apple();
Fruit f3 = new Apple();
List<Fruit> list = new ArrayList<>();
list.add(f1);
list.add(f2);
list.add(f3);
Basket b = new Basket(list);
b.addFruit(list);
System.out.println(b.getSize());
}
}

class Fruit {
}

class Apple extends Fruit {
}

最佳答案

Collection<? extends Fruit> col意味着 colCollectionFruitCollection Fruit 的一些子类,例如 Collection<Apple>Collection<Banana> .

您不能添加 AppleCollection那可能是 Collection<Banana> .

如果您希望能够添加任何Fruit ,将签名更改为:

void addFruit(Collection<Fruit> col)

关于java - Collection <?扩展 T> 意味着?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47200861/

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