我有一个函数,该函数返回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();
消除错误并产生预期的行为。
为什么必须进行强制转换?如何生成不需要强制转换的代码?
问题出在的声明中right
。
而不是
Tree right;
它应该是:
Tree<K, V> right;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句