zoukankan      html  css  js  c++  java
  • <? extends T>和<? super T>

    public class Plate<T> {
    private T item;

    public T getItem() {
    return item;
    }

    public void setItem(T item) {
    this.item = item;
    }

    public Plate(T t){
    this.item = t;
    }

    //内部类-水果,java语法糖,编译的时候也会拆分出来
    class Fruit{

    }

    //内部类-苹果继承自水果
    class Apple extends Fruit{

    }

    @Test
    public void test(){
    //报错原因:苹果是水果,但装苹果的盘子不是装水果的盘子,就是说,容器里面的东西可以具有继承的关系,但容器之间没有继承的关系
    //Plate<Fruit> plate = new Plate<Apple>(new Apple());
    //<? extends Fruit>:能放一切水果的盘子,Plate<? extends Fruit>是Plate<Fruit>以及Plate<Apple>的基类
    Plate<? extends Fruit> plate = new Plate<Apple>(new Apple());
    //上界<? extends T>不能往里存,只能往外取
    //1.不能存入任何元素
    //plate.setItem(new Apple());
    //plate.setItem(new Fruit());

    //2.读取元素
    //Apple apple = plate.getItem();//Error
    Fruit fruit = plate.getItem();
    Object object = plate.getItem();

    Plate<? super Fruit> plate1 = new Plate<Fruit>(new Apple());
    //上界<? super T>不能往外取,只能往里存
    //1.读取出来的东西只能放在他的超类Object中
    //Apple apple = plate1.getItem();//Error
    //Fruit fruit1 = plate1.getItem();//Error
    Object object1 = plate1.getItem();

    //2.存入元素正常
    plate1.setItem(new Apple());
    plate1.setItem(new Fruit());

    /*PECS原则
    最后看一下什么是PECS(Producer Extends Consumer Super)原则,已经很好理解了:
    频繁往外读取内容的,适合用上界Extends。
    经常往里插入的,适合用下界Super。*/
    }
    }
  • 相关阅读:
    经典算法系列二-归并排序
    经典算法系列一-快速排序
    u-boot,linux,文件系统移植笔记1
    ARM函数调用时参数传递规则
    内核移植 nand分区
    LINUX的patch文件打patch
    idea插件使用
    socket通信同步通信,异步通信
    今天学了一个很简易的测试数据库是否连接成功
    wpf中TreeView的使用
  • 原文地址:https://www.cnblogs.com/anjunshuang/p/9340660.html
Copyright © 2011-2022 走看看