我想问一下<? extends A>和<? super A>有什么区别??
还有我在用软件编译的时候
List<? extends Fruit> list3=new ArrayList<Apple>();
List<? super Apple> list5=new ArrayList<Fruit>();
是编译通过的,而
public static void writeTo(List<? super Apple> apple)
{
     apple.add(new Fujin());
}
为什么使用<? super Apple>在add()方法中添加的是Apple的子类而不是Fruit呢??
为什么同样是<? super Apple>前者是基类Fruit,后者是子类Fujin呢??
(我的继承结构是Apple extends Fruit       Fujin extends Apple)

解决方案 »

  1.   

    List<T> list5=new ArrayList<T>();一般这样写,T是Object类型
      

  2.   

    <? extends A>和<? super A>表示泛型的边界不同,
    <? extends A>表示是继承自A的某种类型,A是?的上界
    <? super A>表示是某种子类为A的类型,A是?的下界
    List<? extends Fruit> list3=new ArrayList<Apple>(); 
    List<? super Apple> list5=new ArrayList<Fruit>();
    都可以编译通过,但在add()时是不同的 List<? extends Fruit> flist = new ArrayList<Apple>();
    // Compile Error: can't add any type of object:
    // flist.add(new Apple());
    // flist.add(new Fruit());
    // flist.add(new Object());
    flist.add(null);加注释的都是编译出错的
    因为? extends Fruit表示继承自Fruit的某种类型,List<? extends Fruit>所应该持有的对象是Fruit的子类,而且具体是哪一个子类还是个未知数,所以加入任何Fruit的子类都会有问题,List<? super Apple> list = new ArrayList<Fruit>();   
    list.add(new Apple());
                    // Compile Error: can't add any type of object
    //list.add(new Fruit());
    list.add(new Fujin());加注释的都是编译出错的
    同理,List<? extends Apple>所应该持有的对象是Apple的父类,所以加入Apple没问题,加入Fujin也没问题,因为他们都是Apple,那加入Fruit为什么出错,因为Apple可能还有别的父类,比如Apple继承自Fruit,还实现了Red接口,那他就可以向上转为不同的类型,而且具体是哪一个父类还是个未知数,所以加入任何Apple的父类都会有问题