从列表到集合的java强制转换
我有一个类TreeNode:
public abstract class TreeNode<T>{
.
.
.
public Collection<TreeNode<T>> children;
public void clear(){
if(children == null)
return;
Iterator<TreeNode<T>> iterator = children.iterator();
while(iterator.hasNext()){
TreeNode<T> node = iterator.next();
node.clear();
}
children.clear();
}
.
.
.
}
然后我有一个类ListTreeNode:
public class ListTreeNode<T> extends TreeNode<T>{
.
.
.
public ListTreeNode(T data, List<ListTreeNode<T>> children){
this.data = data;
this.root = null;
this.children = children;
this.childIndex = 0;
}
.
.
.
}
我收到一个编译器错误,说明我无法从List<ListTreeNode<T>>
转换到Collection<TreeNode<T>>
。既然List
是Collection
的子接口,ListTreeNode
是TreeNode
的子类,我难道不能这样做吗?另外,我有一个对应的类SetTreeNode
,它使用Set
而不是List
,并且在我有this.children = children;
的相应构造函数中没有错误
# 1 楼答案
这个问题与将
List<T>
转换为Collection<T>
无关,而与将List<SomeDerivedClass>
转换为List<SomeBaseClass>
有关。Java泛型是不变的,您要寻找的行为是协方差这个问题以前在StackOverflow上被多次提出。这里有一个例子:Is ^{} a subclass of ^{}? Why aren't Java's generics implicitly polymorphic?
# 2 楼答案
一个
List<String>
不是一个List<Object>
。如果是,您可以这样做:如您所见,这将破坏泛型集合的类型安全性
您可能应该使用
Collection<? extends TreeNode<T>>