Search code examples
javagenericsoperandoperands

Operand types error


I tried to implement binarysearchtree ( add method ) with generics but it gives me this kind of error:

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

Code bellow:

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

I thought the problem was that replaced T object could by any type then it could not compare them but i extended the class with Comparable but it did not fix it.

What causes the problem and how do I fix it?


Solution

  • You cannot use < and > operators on any object operands, even if they implement Comparable. You can only apply them to numeric operands.

    replace

    if (value < prev.m_Value)
    

    with

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