当前位置: 代码迷 >> J2EE >> < extends T> 与 < super T>的差别,求解
  详细解决方案

< extends T> 与 < super T>的差别,求解

热度:848   发布时间:2016-04-17 23:11:47.0
<? extends T> 与 <? super T>的区别,求解

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

public class Test {

    public static void main(String[] args) throws SQLException {

       List<? super Fruit> f0=new ArrayList<Fruit>();
       f0.add(new Apple());
       f0.add(new Fruit());
       f0.add(new SupApple());
       
       List<? super Fruit> f1=new ArrayList<Apple>();
       f1.add(new Apple());
       f1.add(new Fruit());
       
       List<? extends Fruit> f2=new ArrayList<Fruit>();
       f2.add(new Apple());
       f2.add(new Fruit());
       
       
       List<? extends Fruit> f3=new ArrayList<Apple>();
       f3.add(new Apple());
       f3.add(new Fruit());
       // f.add(new Apple());
        
       List<? super Apple> f5=new ArrayList<Fruit>();
       f5.add(new Apple());
       f5.add(new SupApple());
       f5.add(new Fruit());
    }
}

class Fruit{
}

class Apple extends Fruit{
}

class SupApple extends Apple{    
}


代码如上,请大家指导,上述代码有多处编译报错,求解:泛型中  extends 和 super的区别!
------解决思路----------------------
List<? extends Fruit> f3的话那么后面ArrayList<..> 中的是Fruit的子类 就是继承自Fruit的
 List<? super Fruit>  f0的话那么后面ArrayList<..> 中的是Fruit的父类 也就是Fruit是他的子类
------解决思路----------------------
lz可以看看这个。应该有帮助
http://hi.baidu.com/augustus_blog/item/d9331b3469b65a1d9dc65e69
------解决思路----------------------
这两个泛型类型
? extends xxx 只能用于方法传参,因为jdk能够确定传入为xxx的子类,返回只能用Object类接收
? supper xxx 只能用于方法返回,jdk能够确定此类的最小继承边界为xxx,只要是这个类的父类都能接收,但是传入参数无法确定具体类型,只能接受null的传入。
? 既不能用于方法参数传入,也不能用于方法返回。

具体参见java核心技术,泛型一章。
  相关解决方案