Java泛型中的标记符含义:
E - Element (在集合中使用,因为集合中存放的是元素)
T - Type(Java 类)
K - Key(键)
V - Value(值)
N - Number(数值类型)
U/S - 表示任意类型
? - 表示不确定的java类型
package com.ym.learn;
/**
* @Deacription 盘子
* @Author yumifen
* @Date 2020/9/29 10:42
* @Version 1.0
**/
public class Plate<T> {
private T item;
public Plate(T item) {
this.item = item;
}
public T getItem() {
return item;
}
public void setItem(T item) {
this.item = item;
}
public static void main(String[] args) {
//上界<? extends T>不能往里存,只能往外取
//(1).<? extends Fruit>会使往盘子里放东西的set( )方法失效,但取东西get( )方法还有效
//(2).取出来的东西只能存放在Fruit或它的基类里面,向上造型。
Plate<? extends Fruit> p1 = new Plate<Apple>(new Apple()); //苹果盘
Fruit apple = p1.getItem();
Plate<? extends Fruit> p3 = new Plate<Banana>(new Banana()); //香蕉盘
Fruit Banana = p3.getItem();
//因为规定的下界,对于上界并不清楚,所以只能放到最根本的基类Object中
//因为下界规定了元素的最小粒度的下限,实际上是放松了容器元素的类型控制。
//既然元素是Fruit的基类,那往里存粒度比Fruit小的都可以。
//但往外读取元素就费劲了,只有所有类的基类Object对象才能装下。但这样的话,元素的类型信息就全部丢失
Plate<? super Fruit> p2 = new Plate<Fruit>(new Apple()); //苹果盘
p2.setItem(new Banana());
}
}
//Lev 1
class Food{}
//Lev 2
class Fruit extends Food{}
class Meat extends Food{}
//Lev 3
class Apple extends Fruit{}
class Banana extends Fruit{}
class Pork extends Meat{}
class Beef extends Meat{}
//Lev 4
class RedApple extends Apple{}
class GreenApple extends Apple{}