2016-02-29 96 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); 

那麼就會讓編譯器保持泛型類型參數的跟蹤和做所有的類型檢查需要的地方。