美文网首页
PECS原则

PECS原则

作者: laosijikaichele | 来源:发表于2018-02-19 19:16 被阅读16次

    PECS原则:Producer Extends Consumer Super

    频繁往外读取内容的,适合用上界Extends。
    经常往里插入的,适合用下界Super。

            List <? extends Fruit> extendsList = new ArrayList();
            extendsList.add(new Object()); //ERROR
            extendsList.add(new Fruit()); //ERROR
            extendsList.add(new Apple()); //ERROR
            extendsList.add(new Pear()); //ERROR
            Object e1 = extendsList.get(0);
            Fruit e2 = extendsList.get(0);
            Apple e3 = extendsList.get(0); //ERROR
            Pear e4 = extendsList.get(0); //ERROR
    
    
            List <? super Fruit> superList = new ArrayList();
            superList.add(new Object()); //ERROR
            superList.add(new Fruit());
            superList.add(new Apple());
            superList.add(new Pear());
            Object s1 = superList.get(0);
            Fruit s2 = superList.get(0); //ERROR
            Apple s3 = superList.get(0); //ERROR
            Pear s4 = superList.get(0); //ERROR
    

    参考:https://itimetraveler.github.io/2016/12/27/%E3%80%90Java%E3%80%91%E6%B3%9B%E5%9E%8B%E4%B8%AD%20extends%20%E5%92%8C%20super%20%E7%9A%84%E5%8C%BA%E5%88%AB%EF%BC%9F/

    相关文章

      网友评论

          本文标题:PECS原则

          本文链接:https://www.haomeiwen.com/subject/jrqwtftx.html