gpt4 book ai didi

java - 为什么我不能将 B 父类(super class)的对象放入 Container<? super B>?

转载 作者:行者123 更新时间:2023-12-01 14:20:35 24 4
gpt4 key购买 nike

<分区>

我有下面的代码。看来我不能放类 Nonlife 的对象那是类的父类(super class) Vehicle放入 Collection<? super Vehicle> 类型的容器中ALTHOUGH 通配符类型中有一个关键字“super”,并且只有 Vehicle 类的对象和 SUV那是 Vehicle 类的子类是可行的。有人可以给我一些建议吗?

public class SUV extends Vehicle

public class Vehicle extends Nonlife implements Externalizable

public class Nonlife extends Thing

public class Thing implements Comparable<Thing>, Serializable

public class SupperWildcardTest20200830 {

public static void main(String[] args) {
Collection<Thing> coll = new ArrayList<>();
appendVehicle2Collection(coll);
appendSuv2Collection(coll);
for (Thing el: coll) {
System.out.println("" + el);
}
}

public static void appendVehicle2Collection(Collection<? super Vehicle> coll) {
coll.add(new Vehicle());
}

public static void appendSuv2Collection(Collection<? super Vehicle> coll) {
coll.add(new SUV());
}

public static void appendNolife2Collection(Collection<? super Vehicle> coll) {
/**
* incompatible types: Nonlife cannot be converted to CAP#1
* where CAP#1 is a fresh type-variable:
* CAP#1 extends Object super: Vehicle from capture of ? super Vehicle
*/
coll.add(new Nonlife());
}
}

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