PECS

java 中 PECS问题

<? extends T>:是指 “上界通配符(Upper Bounds Wildcards)”
<? super T>:是指 “下界通配符(Lower Bounds Wildcards)
话不多说上代码-_-
package test;

import java.util.ArrayList;
import java.util.List;

public class Demo04 {

    public static void main(String[] args) {

        Plate<Fruit> p1 = new Plate<>(new Apple());
        // 不能set元素   且拿出的元素只能是fruit及其超类
        Plate<? extends Fruit> plate = new Plate<Apple>(new Apple());
//        plate.setFruit(new Apple());  // 无法设置
//        Apple a = plate.getFruit(); // error
        Fruit b = plate.getFruit(); // ok
        Object c = plate.getFruit(); // ok

        // 可以set\get 但是get只能拿到object
        Plate<? super Fruit> plate1 = new Plate<Fruit>(new Apple());
//        plate1.setFruit(new Demo04()); // error
        plate1.setFruit(new Fruit()); // ok
//        Apple d = plate1.getFruit(); // error
        Object e = plate1.getFruit(); // ok
//        Fruit f = plate1.getFruit(); // error

        List<Apple> ll = new ArrayList<>();
        ll.add(new Apple());
        ll.add(new Apple());
        // 上界通配符  无法添加元素
        List<? extends Fruit> list = new ArrayList<>(ll); // 通过构造器可以传入内容
//        Apple bb = list.get(1); // error
        Fruit aa =  list.get(1); // ok   只能通过fruit及其超类获取
//        list.add(new Apple()); // 无法设置

        // 下界通配符   只能添加fruit及其子类
        List<? super Fruit> list1 = new ArrayList<>();
        list1.add(new Apple());
//        list1.add(new Object()); // error
//        Apple g = list1.get(1); // error
        Object h = list1.get(1); // ok
    }
}

class Plate<T> {

    private T fruit;

    Plate(T fruit) {
        this.fruit = fruit;
    }

    public T getFruit() {
        return fruit;
    }

    public void setFruit(T fruit) {
        this.fruit = fruit;
    }
}

class Fruit {

}

class Apple extends Fruit {

}

猜你喜欢

转载自www.cnblogs.com/blogfyang/p/12171652.html