使用Generic Comparable <t>数据在Java中实现二叉树?</t>

时间:2014-11-26 17:39:47

标签: java generics binary-tree comparable

问:在我下面的二叉树实现中,为什么编译器会在

处窒息

if (data.compareTo(this.data) <= 0)

生产

Error: incompatible types: java.lang.Comparable<T> cannot be converted to T

datathis.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;
  }  

以下是来自二叉树的更标准实现的剪辑。编译好了。但是我仍然不明白为什么这比我上面的“更好”(根据编译器)实现。

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;
  }

2 个答案:

答案 0 :(得分:6)

如果某些内容为Comparable<T>,则其与T相当,与Comparable<T>无法比较。这就是第二个片段的工作原理。

答案 1 :(得分:1)

查看javadoc of ComparablecompareTo(T)接口提供的Comparable。此方法允许将实现此接口的T类的对象实例与另一个T实例进行比较。在您的第一个示例中,您将Comparable<T>Comparable<T>进行比较(而不是T

这应该有效:

public class MyBinaryTreeNodeG<T> {

    Comparable<T> data;

    // ...

    public MyBinaryTreeNodeG<T> addChild(final T data) {
        if (this.data.compareTo(data) <= 0) {
        } else {
        }
        // ...
    }
}