Java泛型上下界

有如下类的继承关系

 // ok
Fruit apple = new Apple(); 

 

List<Fruit> plate = new ArrayList<Apple>();

它会在Idea里报红线,运行会报错:java: 不兼容的类型: java.util.ArrayList<Apple>无法转换为java.util.List<Fruit>,显然在集合间不存在继承引用关系

 

泛型的上界, ? extends T

使用泛型的上界,? extends Fruit,就能解决如上问题

List<? extends Fruit> plate = new ArrayList<Apple>();

只能取,不能存

【只能取】

List<Apple> appleList = new ArrayList<>();
 appleList.add(new Apple());
 appleList.add(new Apple());
 List<? extends Fruit> plate = appleList;
 Fruit fruit = plate.get(0);

【不能存】

 使用

List<? extends Fruit> plate = Arrays.asList(new Apple(), new Banana());

 Fruit apple = plate.get(0);
 Fruit banana = plate.get(1);

在这种情况下,这个plate真的成了能装任何水果的盘子,里边有Apple和Banana,取出来之后确实都是Fruit。

 

泛型的下界, ? super T

 

能存

// 定义了一个plate,它的下界为 ? super Apple
List<? super Apple> plate = new ArrayList<>();

plate.add(new Apple());
plate.add(new RedApple());
plate.add(new GreenApple());

也能取

 不过取出来的东西都是Object,使其中元素的类型失效了,而且因为? super Apple这个范围太大了,不知道拿出来是具体什么类型,只能用最高的Object来进行引用了

posted @ 2025-02-27 18:05  KLAPT  阅读(9)  评论(0)    收藏  举报