操作数类型错误

Operand types error

我试图用泛型实现 binarysearchtree(add 方法),但它给了我这种错误:

genericstree.java:36: error: bad operand types for binary operator '>'
            if ( value > iterator.m_Value )
                       ^
  first type:  T
  second type: T
  where T is a type-variable:
    T extends Comparable<T> declared in class BinarySearchTree
genericstree.java:42: error: bad operand types for binary operator '<'
        if ( value < prev.m_Value )
                   ^
  first type:  T
  second type: T
  where T is a type-variable:
    T extends Comparable<T> declared in class BinarySearchTree
2 errors

代码如下:

class BinarySearchTree<T extends Comparable<T>>
{
    class Node<T extends Comparable<T>>
    {
        Node<T> left;
        Node<T> right;
        T        m_Value;

        Node( T value )
        {
            left = null;
            right = null;
            m_Value = value;
        }
    }

    Node<T> m_Root;

    BinarySearchTree() { m_Root = null; }
    void addNode( T value )
    {
        Node<T> tmp = new Node<T>( value );
        if ( m_Root == null )
        {
            tmp.m_Value = value;
            m_Root = tmp;
            return;
        }

        Node<T> iterator = m_Root;
        Node<T> prev = m_Root;
        while ( iterator != null )
        {
            prev = iterator;
            if ( value > iterator.m_Value )
                iterator = iterator.right;
            else
                iterator = iterator.left;
        }

        if ( value < prev.m_Value )
            prev.left = tmp;
        else
            prev.right = tmp;
    }
}

我认为问题是替换的 T 对象可以是任何类型然后它无法比较它们但是我用 Comparable 扩展了 class 但它没有修复它。

导致问题的原因是什么,我该如何解决?

您不能对任何对象操作数使用 <> 运算符,即使它们实现了 Comparable。您只能将它们应用于数字操作数。

替换

if (value < prev.m_Value)

if (value.compareTo(prev.m_Value) < 0)