通配符<? extends T>和<? super T>区别及使用场景
<? extends T>和<? super T>理解与使用
package com.orchard.common.annotation;
public class Plate<T> {
private T item;
public Plate(T t) {
this.item = t;
}
public T get() {return item;}
public void set(T item) {this.item = item;}
}
class Food {}
class Fruit extends Food {}
class Apple extends Fruit {}
class Apple1 extends Apple {}
class Apple2 extends Apple {}
class Test {
public static void main(String[] args) {
/**
* 频繁往外读取内容的,适合用上界Extends。
*/
//申明Plate容器的元素是Fruit类或其子类
Plate<? extends Fruit> p1 = new Plate<Apple>(new Apple());
//编译器并不知道添加的元素和Plate容器申明的元素关系,所以报错
//p1.set(new Apple1());//error
//得到容器Plate的基类
Fruit fruit = p1.get();
/**
* 经常往里插入的,适合用下界Super。
*/
//申明Plate容器的元素是Fruit类或其父类
Plate<? super Fruit> p2 = new Plate<Food>(new Food());
//编译器知道Plate容器申明的元素必是添加元素的基类(Food类或其子类任意添加)
p2.set(new Fruit());
p2.set(new Apple1());
//
Object object = p2.get();
}
}