考虑以下场景,FastCar 类扩展自 Car 类:
public class FastCar extends Car {}
主方法中的代码片段:
Set<? extends Car> mySet6 = null;
mySet6.add(new FastCar()); //<-----compile error
编译错误详细信息:
(The method add(capture#4-of ? extends Car) in the type Set<capture#4-of ?
extends Car> is not applicable for )
我很困惑为什么 FastCar 对象不能放入“对象扩展汽车集”中,任何人都可以帮忙澄清吗?谢谢。
最佳答案
泛型的目的是提供类型安全操作(并禁止非类型安全操作)。
对于 Set<? extends Car>
类型的变量编译器允许分配 Set<SlowCar>
类型的值因为Set<SlowCar>
延伸Set<? extends Car>
。如果您要这样做,请添加 FastCar
到 Set
只允许 SlowCar
s 显然是一个错误。因此添加 FastCar
到 Set
允许 ? extends Car
也一定不允许,因为它不是类型安全的。
Set<SlowCar> slowSet = ...;
slowSet.add(new FastCar()); // Obviously ERROR, FastCar does not extend SlowCar
Set<? extends Car> carSet = slowSet; // Allowed, valid (SlowCar extends Car)
carSet.add(new FastCar()); // Error, because carSet might be
// and actually is a set of SlowCars
就您而言Set<Car>
应该使用:
Set<Car> cars = ...;
cars.add(new FastCar()); // Valid, FastCar extends Car
cars.add(new SlowCar()); // Valid, SlowCar extends Car
关于Java 泛型查询(上限通配符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25759710/