2014-11-08 48 views
0

我有一個函數返回一個通用類K的類型,它擴展了Comparable接口。這個函數遞歸地調用它自己。有趣的是,當它被稱爲我收到錯誤Type mismatch: cannot convert from Comparable to K.「類型不匹配」函數遞歸返回

public class NonEmptyTree<K extends Comparable<K>, V> implements Tree<K, V> { 
    Tree right; 
    K key; 
    ... 
    public K max() throws EmptyTreeException { 
     try { 
      return right.max(); // "Type mismatch: cannot convert from Comparable to K" 
     } catch (EmptyTreeException e) { 
      return key; 
     } 
    } 
    ... 
} 

改變return語句return (K) right.max();消除錯誤併產生預期的行爲。

爲什麼演員是必要的,我怎樣才能生成代碼,這樣就不需要演員?

+0

是''型的K' key'? – Tom 2014-11-08 02:27:27

+0

a)[PECS](http://stackoverflow.com/q/17192772/995891):'>'b)where/how是如何定義的? – zapl 2014-11-08 02:31:00

+0

@Tom是的,''鍵是'K'類型。 @zapl'right'的類型是'Tree',類就是這個類的擴展。 – ahe 2014-11-08 02:35:14

回答

1

問題出在right的聲明中。

不是

Tree right; 

它應該是:

Tree<K, V> right;