【发布时间】:2011-12-25 16:34:23
【问题描述】:
我有一个类 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; 的相应构造函数中没有错误。
【问题讨论】:
-
我真的不明白为什么你必须传递 List
> 而不是 List >,这真的是故意的吗?也就是说,由于 ListTreeNode 扩展了 TreeNode,因此 List > 不能分配给 Collection > 而是 Collection> -
@DylanSmith:除了一个处理 C#,而这个问题处理 Java。 (虽然答案相似,但它们并不相同。)我能找到的第一个副本是this one,但我敢肯定还有更多。
-
呃,没注意到 Java...没关系
-
我故意传入一个 List
>,这样你就不能传入任何其他派生自 TreeNode 的类。我最初将 children 更改为 Collection> 但我收到了一些警告。所以我把它改成了 Collection> 并消除了警告。谢谢:)
标签: java inheritance collections casting