有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从列表到集合的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>>。既然ListCollection的子接口,ListTreeNodeTreeNode的子类,我难道不能这样做吗?另外,我有一个对应的类SetTreeNode,它使用Set而不是List,并且在我有this.children = children;的相应构造函数中没有错误


共 (2) 个答案

  1. # 2 楼答案

    一个List<String>不是一个List<Object>。如果是,您可以这样做:

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

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

    您可能应该使用Collection<? extends TreeNode<T>>