[英]Java generics query (Upper Bounded Wildcards)
考虑以下情况,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对象不能放入“对象集Car扩展”中,任何人都可以帮助澄清? 谢谢。
泛型的目的是提供类型安全的操作(并禁止非类型安全的操作)。
对于Set<? extends Car>
类型的变量 Set<? extends Car>
编译器允许分配类型为Set<SlowCar>
的值,因为Set<SlowCar>
扩展Set<? extends Car>
Set<? extends Car>
。 如果这样做,将FastCar
添加到只允许SlowCar
的Set
显然是错误的。 因此,将FastCar
添加到Set
可以? extends Car
? 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教程中有关通配符的情况很好地解释了这种情况。 我将重新编写它(我将类型和对象名称重命名):
您应该能够弄清楚为什么不允许使用上面的代码。 mySet6.add()
的参数类型为? extends Car
? extends Car
-未知亚型Car
。 由于我们不知道它是什么类型,所以我们不知道它是否是FastCar
的超类型; 它可能是也可能不是这种超类型,因此在FastCar
传递FastCar
是FastCar
。
http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.