日期:2014-05-20 浏览次数:20937 次
List<? extends MyInterface> list =new ArrayList(); list.add(new A()); //报错 MyInterface objectImpl=new A(); list.add(objectImpl); //报错
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;
}
}
List<? super MyInterface> list =new ArrayList(); //使用super list.add(new A()); MyInterface objectImpl=new A(); list.add(objectImpl);
------解决方案--------------------
(1) 向下匹配:<? extends Number>
表示该集合元素可以为Number类型及其子类型(包括接口)
(2) 向上匹配:<? super Number>
表示该集合元素可以为Number类型及其父类型
------解决方案--------------------
以<? extends Type>作为返回值的话貌似就只能往外取值了, 只能往里放null。。。
------解决方案--------------------