2016-02-29 62 views
1

我不明白为什么Java编译器给我“未选中转换”警告在以下情况: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()函数不返回列表类型,则它返回列表< NodeTree < T>>类型。

请帮我理解。

+0

在课程名称前写上'@SurpressWarning(“all”)' –

回答

1

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

1

您正在将原始类型与非原始类型混合在一起。这基本上是BadThing(tm)。因此,您的代码

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

创建节点变量作为原始类型,即使初始化程序不是原始类型。因此,对于编译器,node.getChilds()的类型实际上是List而不是List<NodeTree<Integer>>,因为您可能一直期待。

如果你改变它是...

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

那么就会让编译器保持泛型类型参数的跟踪和做所有的类型检查需要的地方。