定义
<? extends T>:是指 “上界通配符(Upper Bounds Wildcards)
<? super T>:是指 “下界通配符(Lower Bounds Wildcards)
示例
public class Fruit {
private String name;
public Fruit(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Apple extends Fruit{
public Apple(String name) {
super(name);
}
}
public static void test1(List<? super Fruit> list) {
//list的泛型一定是Fruit或者Fruit的父类,所以通过强转能够添加Fruit或者Fruit的子类
// get的时候,不知道具体类型,所以只能用Object接收
list.add(new Apple(null));
Object o = list.get(0);
}
public static void test2(List<? extends Fruit> list) {
/*list的泛型一定是Fruit或者Fruit的子类,如果当前泛型为Apple,
接收参数类型为Fruit,那么Fruit无法强转成Apple,所以不能使用add方法
get时,由于当前泛型是Fruit的子类,所以可以用Fruit接收
*/
list.add(null);
Fruit f = list.get(0);
}