繁体   English   中英

Java泛型查询(上界通配符)

[英]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添加到只允许SlowCarSet显然是错误的。 因此,将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传递FastCarFastCar

http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM