具有内在类和比较的泛型

时间:2014-02-08 07:16:43

标签: java generics

我对java中的泛型不是很了解。当内部类存在时,我对如何处理泛型感到困惑。下面的代码实现二进制搜索树给我一个错误。

public class BST <T extends Comparable<T>>
{
  Node<T> root;

 private class Node<T extends Comparable<T>>
   {
    T data;
    Node<T> left, right;

    Node(T data)
     {
      this.data = data;
      left= right = null;    
     }

   }

  public void insert(Node<T> start, T data)
   {     
     if(start == null) 
           { 
            Node<T> newnode = new Node<T> (data);          
            start = newnode;
            return;
            }

     else if( data < start.data )   //ERROR LINE
                insert(start.left, data);
     else if ( data > start.data )   //ERROR LINE               
                insert(start.right, data);

     else 
       {
           //no need to do anything as the elements has the same key as the new key
          return;
      }
   }

错误:

BST.java:29: error: bad operand types for binary operator '<'
     else if( data < start.data )
 first type:  T  second type: T  where T is a type-variable: T extends Comparable<T> declared in class BST.

1 个答案:

答案 0 :(得分:0)

任何扩展Comparable的对象都不会自动赋予它对数值比较运算符的支持,而是指定compareTo()方法:

  

将此对象与指定的订单对象进行比较。返回负整数,零或正整数,因为此对象小于,等于或大于指定对象。

所以使用类似的东西:

data.compareTo(start.data) < 0

应该这样做。