2012-09-07 51 views
0

我有這樣一個類:泛型和unchecked錯誤

class BSTNode<K extends Comparable, V> { 
    K key; 
    BSTNode(K key, V value) { ... } 
    } 

然後我使用

node.key.compareTo(root.key) >= 0 

noderootBSTNode。在那一行中,我得到一個未經檢查的錯誤。爲什麼?

warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type Comparable 
     } else if (node.key.compareTo(root.key) >= 0) { // new node >= root 
           ^
    where T is a type-variable: 
    T extends Object declared in interface Comparable 
1 warning 

在我的理解,在BSTNode定義,K應該擴展/實現Comparable。那麼node.key.compareTo(root.key)應該可以嗎?

+0

你能告訴我們'node'和'root'的變量聲明嗎? – Matt

回答

4

Comparable也被基因化。請嘗試以下操作:

class BSTNode<K extends Comparable<? super K>, V> { ... } 

此外,請確保您的聲明使用正確的類型:

// will cause the warning 
BSTNode root = new BSTNode<Integer, Integer>(1, 1); 
// will NOT cause the warning 
BSTNode<Integer, Integer> root = new BSTNode<Integer, Integer>(1, 1); 
+0

爲獲得最佳效果使用'K延伸可比較>' – newacct

+0

感謝您的提示,我相應地更新了答案。 – Matt

2

類應實現的可比較的一個仿製版本。在你的情況下Comparable<K>

class BSTNode<K extends Comparable<K>, V> { 
    K key; 
    BSTNode(K key, V value) {} 
} 
+0

爲獲得最佳效果使用'K延伸可比較的>' – newacct