java泛型的简单问题(困扰我很久了)
- Java code
List<? extends MyInterface> list =new ArrayList();list.add(new A()); //报错MyInterface objectImpl=new A();list.add(objectImpl); //报错
这里list不能添加任何东西!! 到底要怎样把A的实例放到这个list中去哦?
- Java code
public interface MyInterface{}public class A implements MyInterface{}背景:
我在项目中经常遇到集合中元素限制为某个接口类型,如下面的树节点模型:
- Java code
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<MyInterface> list =new ArrayList<MyInterface>();
[解决办法]
- Java code
List<? super MyInterface> list =new ArrayList(); //使用superlist.add(new A()); MyInterface objectImpl=new A();list.add(objectImpl);
[解决办法]
(1) 向下匹配:<? extends Number>
表示该集合元素可以为Number类型及其子类型(包括接口)
(2) 向上匹配:<? super Number>
表示该集合元素可以为Number类型及其父类型
[解决办法]
以<? extends Type>作为返回值的话貌似就只能往外取值了, 只能往里放null。。。
[解决办法]