【问题标题】:Casting From A List To A Collection从列表转换为集合
【发布时间】: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&lt;ListTreeNode&lt;T&gt;&gt; 转换为 Collection&lt;TreeNode&lt;T&gt;&gt;。我不应该能够吗,因为ListCollection 的子接口,而ListTreeNodeTreeNode 的子类?另外,我有一个相应的类 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


【解决方案1】:

List&lt;String&gt; 不是List&lt;Object&gt;。如果是,您可以这样做:

List<String> listOfStrings = new ArrayList<String>();
List<Object> listOfObjects = listOfStrings;
listOfObjects.add(new Integer(3));

如您所见,这会破坏泛型集合的类型安全性。

您可能应该使用Collection&lt;? extends TreeNode&lt;T&gt;&gt;

【讨论】:

    【解决方案2】:

    这个问题与将List&lt;T&gt; 转换为Collection&lt;T&gt; 无关,而与将List&lt;SomeDerivedClass&gt; 转换为List&lt;SomeBaseClass&gt; 无关。 Java 泛型是不变的,您正在寻找的行为是协变

    这个问题之前在 StackOverflow 上已经提出过很多次了。这是一个例子:Is List&lt;Dog&gt; a subclass of List&lt;Animal&gt;? Why aren't Java's generics implicitly polymorphic?

    【讨论】:

    • 谢谢。我试图搜索它,但它一定是我找到的。
    猜你喜欢
    • 2013-12-16
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 2022-11-12
    • 2010-10-03
    • 1970-01-01
    相关资源
    最近更新 更多