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;
}
}
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;
}
}
List<MyInterface> list =new ArrayList<MyInterface>();
List<? super MyInterface> list =new ArrayList(); //使用super
list.add(new A());
MyInterface objectImpl=new A();
list.add(objectImpl);
表示该集合元素可以为Number类型及其子类型(包括接口)
(2) 向上匹配:<? super Number>
表示该集合元素可以为Number类型及其父类型
还有 泛型对象进行引用传递时,类型必须一致,若要强制传参过去,只有将接收参数方法的泛型去掉
类名称<? extends 类> 可以接收任意类型的数据,但此内容无法直接用<?>修饰的泛型对象进行修改——即 :只能接受,不能修改
后来看了这一篇文章才恍然大悟。
http://blog.csdn.net/daniel_h1986/article/details/5708605