“类型不匹配”函数递归返回

问题描述:

我有一个函数返回一个通用类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

问题出在right的声明中。

不是

Tree right; 

它应该是:

Tree<K, V> right;