low*_*rul 0 java generics binary-tree comparable
问:在我下面的二叉树实现中,为什么编译器会窒息
if (data.compareTo(this.data) <= 0),
生产
Error: incompatible types: java.lang.Comparable<T> cannot be converted to T?
这两个data和this.data的类型Comparable<T>,应该能够使用或者是一个参数传递给的compareTo()方法,对吧?好吧,显然不是.但我真的不明白为什么.仿制药仍然令我感到困惑.
public class MyBinaryTreeNodeG<T>{
Comparable<T> data;
MyBinaryTreeNodeG<T> parent;
MyBinaryTreeNodeG<T> left;
MyBinaryTreeNodeG<T> right;
public MyBinaryTreeNodeG(Comparable<T> data){
this.data = data;
}
public MyBinaryTreeNodeG<T> addChild(Comparable<T> data){
if (data.compareTo(this.data) <= 0) { //this is the line on which the compiler chockes
//check if left tree node is null. If so, add. Otherwise, recurse.
} else {
//same for the right tree node
return null;
}
Run Code Online (Sandbox Code Playgroud)
以下是来自二叉树的更标准实现的剪辑.编译好了.但我仍然不明白为什么这比我上面的"更好"(根据编译器)实现.
public class MyBinaryTreeNodeG<T extends Comparable<T>>{
T data;
MyBinaryTreeNodeG<T> parent;
MyBinaryTreeNodeG<T> left;
MyBinaryTreeNodeG<T> right;
public MyBinaryTreeNodeG(T data){
this.data = data;
}
public MyBinaryTreeNodeG<T> addChild(T data){
if (data.compareTo(this.data) <= 0) {
//left node stuff
} else {
//right node stuff
return null;
}
Run Code Online (Sandbox Code Playgroud)