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

标签 java generics

考虑以下场景,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> 。如果您要这样做,请添加 FastCarSet只允许 SlowCar s 显然是一个错误。因此添加 FastCarSet允许 ? 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/

相关文章:

java - 如何在 WebDriver 中遵循重定向

java - 将图像从 Android 客户端上传到 Salesforce 自定义对象

Java 泛型返回类型

c# - 具有多个 child 的通用基类

c# - 如果 <T> 是动态的,我如何测试 Enumerable<T> 中的 <T> 是否实现了接口(interface)?

java - 使用数组列表的大小

java - HBase - 带偏移量的值过滤器?

Java Swing 类无法转换为 DefaultListModel

scala - 使用案例类No Manifest的Scala Dynamic Parse Json可用于T

f# - 在不同的泛型实例中实现相同的接口(interface)