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
网友评论