2

The compiler says " cannot find symbol: method compareTo(java.lang.Object) ". Could you please advice where is the mistake here?

Here is the part of the code:

public class OBTComparable<ObjectType> implements Comparable<OBTComparable>
{
    public OTBComparable leftNode = null;
    public OBTComparable mainNode = null;
    public OBTComparable rightNode = null;
    public ObjectType object = null;

    public OBTComparable(ObjectType requiredObject)
    {
        object = requiredObject;
    }

    @Override
    public int compareTo(OBTComparable other)
    {
        if(object.compareTo(other.object) == 0)
            return 0;
        else 
            if (object.compareTo(other.object) > 0)
                return 1;
            else return -1;
    }
}

3 Answers3

4

You need to scope ObjectType to Comparable too, because OBTComparable is delegating compareTo() to ObjectType:

If you change <ObjectType> to <ObjectType extends Comparable<ObjectType>>, it will compile:

public class OBTComparable<ObjectType extends Comparable<ObjectType>> implements Comparable<OBTComparable>
Bohemian
  • 412,405
  • 93
  • 575
  • 722
3

I think this is the proper code you are looking for (I replaced ObjectType with T for clarity):

class OBTComparable<T extends Comparable<? super T>> implements Comparable<OBTComparable<T>> {
    public OBTComparable<T> leftNode = null;
    public OBTComparable<T> mainNode = null;
    public OBTComparable<T> rightNode = null;
    public T object = null;

    public OBTComparable(T requiredObject) {
        object = requiredObject;
    }

    @Override
    public int compareTo(OBTComparable<T> other) {
        if (object.compareTo(other.object) == 0) {
            return 0;
        } else if (object.compareTo(other.object) > 0) {
            return 1;
        } else return -1;
    }
}

What did I change here:

  1. OBTComparable uses a type parameter, so you should show it when you implement Comparable. Therefore you have implements Comparable<OBTComparable<T>> instead of simply implements Comparable<OBTComparable>.
  2. You compare two objects in the compareTo method, but are they comparable? To make sure this requirement is fulfilled, you should write OBTComparable<T extends Comparable<T>> instead of just OBTComparable<T>. Then you will know that you can call compareTo.
Malcolm
  • 41,014
  • 11
  • 68
  • 91
2

ObjectType must also implement Comparable<ObjectType>.

And if you do this, I believe that this:

public int compareTo(OBTComparable other)
{
    if(object.compareTo(other.object) == 0)
        return 0;
    else 
        if (object.compareTo(other.object) > 0)
            return 1;
        else return -1;
}

can be simplified to this:

public int compareTo(OBTComparable other)
{
    return object.compareTo(other.object);
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373