【问题标题】:Java generic list gives me warningJava 通用列表给了我警告
【发布时间】:2016-02-29 12:03:18
【问题描述】:

我不明白为什么 Java 编译器在以下情况下会给出“未经检查的转换”警告:

我有这门课:

public class NodeTree<T> {
   T value;
   NodeTree parent;
   List<NodeTree<T>> childs;

   NodeTree(T value, NodeTree parent) {
       this.value = value;
       this.parent = parent;
       this.childs = null;
   }

   public T getValue() { return value; }
   public void setValue(T value) { this.value = value; }

   public NodeTree getParent() { return parent; }
   public void setParent(NodeTree parent) { this.parent = parent; }

   public List<NodeTree<T>> getChilds() {
       if (this.childs == null) {
           this.childs = new LinkedList<NodeTree<T>>();
       }
       return this.childs;
   }
}

在主课中我有以下说明:

NodeTree node = new NodeTree<Integer>(10, null);

NodeTree<Integer> child = new NodeTree<Integer>(20, node);      
List<NodeTree<Integer>> childs = node.getChilds();

childs.add(child);

我无法解释为什么我会在这种类型的 getChilds() 行上收到警告:

warning: [unchecked] unchecked conversion
List<NodeTree<Integer>> childs = node.getChilds();
                                               ^
required: List<NodeTree<Integer>>
found:    List
1 warning

getChilds() 函数不返回 List 类型,它返回 List > 类型。

请帮我理解。

【问题讨论】:

  • 在类名前写@SurpressWarning("all")

标签: java list generics unchecked unchecked-conversion


【解决方案1】:

编码NodeTree&lt;Integer&gt; node = new NodeTree&lt;&gt;(10, null);不是更好吗 而不是 NodeTree node = new NodeTree&lt;Integer&gt;(10, null); ?然后编译器就会知道node的类型参数。

【讨论】:

    【解决方案2】:

    您将原始类型与非原始类型混为一谈。这基本上是一个坏事(tm)。所以你的代码

    NodeTree node = new NodeTree<Integer>(10, null);
    

    将节点变量创建为原始类型,即使初始化程序不是原始类型。因此,对于编译器,node.getChilds() 的类型实际上是 List,而不是您可能期望的 List&lt;NodeTree&lt;Integer&gt;&gt;

    如果你把它改成……

    NodeTree<Integer> node = new NodeTree<Integer>(10, null);
    

    那么这将允许编译器跟踪泛型类型参数并进行所需的所有类型检查。

    【讨论】:

      猜你喜欢
      • 2017-02-20
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 1970-01-01
      相关资源
      最近更新 更多