List<? extends MyInterface> list =new ArrayList();
list.add(new A());        //报错
MyInterface objectImpl=new A();
list.add(objectImpl);  //报错这里list不能添加任何东西!! 到底要怎样把A的实例放到这个list中去哦?public interface MyInterface{}
public class A implements MyInterface{}
背景:
我在项目中经常遇到集合中元素限制为某个接口类型,如下面的树节点模型:public interface TreeNode {
    //....一些方法    /**
     * 获取子节点集合.     叶节点返回<code>null</code>。
     *
     * @return 子节点集合或<code>null</code>
     */
    public Collection<? extends TreeNode> getChildren();    //此处返回值若换成Collection<TreeNode>,那么该接口在实现上比较麻烦
}public class ArrayListTreeNode{
    private ArrayList<ArrayListTreeNode> children;          //此处的泛型只能是同一个类
    @Override
    public ArrayList<? extends TreeNode> getChildren(){// 如果这里返回值是ArrayList<TreeNode>的话,外面使用起来麻烦,比如说添加子节点
          return children;
    }
}

解决方案 »

  1.   

    得这样吧
    List<MyInterface> list =new ArrayList<MyInterface>();
      

  2.   


    List<? super MyInterface> list =new ArrayList(); //使用super
    list.add(new A());        
    MyInterface objectImpl=new A();
    list.add(objectImpl);  
      

  3.   

    (1) 向下匹配:<? extends Number>
    表示该集合元素可以为Number类型及其子类型(包括接口)
    (2) 向上匹配:<? super Number>
    表示该集合元素可以为Number类型及其父类型
      

  4.   

    我非常清楚板凳兄的意思,只是项目中使用<? extends Type> 作为返回值比使用<Type>作为返回值会方便很多。
      

  5.   

    以<? extends Type>作为返回值的话貌似就只能往外取值了, 只能往里放null
      

  6.   


    还有   泛型对象进行引用传递时,类型必须一致,若要强制传参过去,只有将接收参数方法的泛型去掉
          
           类名称<? extends 类>    可以接收任意类型的数据,但此内容无法直接用<?>修饰的泛型对象进行修改——即 :只能接受,不能修改
      

  7.   

    刚开始的时候没有理解到。
    后来看了这一篇文章才恍然大悟。
    http://blog.csdn.net/daniel_h1986/article/details/5708605