M.Cob M.Cob - 1 month ago 8
Java Question

BinaryTree Generic CompareTo

Ok, so I'm I'm working on a school project where we implement a Binary

TreeMap
and given a basic template to fill out. I'll try to not dump all of the code but here's where I'm hitting a wall. I need to be able to compare keys so insert new elements, properly search and whatnot. But I keep getting a Bad Operand error.

private class Element {
K key;
V value;
public Element(K key, V value) {
this.key = key;
this.value = value;
}
public int compareTo(Element that) {
if (key < that.key) //Error Here
return -1;
else if(key > that.key) //And here
return 1;
else
return 0;
}
}


Now this class is a subclass of the TreeMap class. Again I won't dump the whole code, but the header is like so:

public class TreeMap<K extends Comparable<K>,V> implements MyMap<K,V>


Now everywhere I look seems to point that having
K extends Comparable<K>
should allow these to be comparable, but they're not. This header was provided by the teacher, so I don't think it needs to be altered. Am I just overlooking or forgetting something?

Answer

You can't compare Comparable objects using < and >. Those are only for numeric values. Instead, you can use something like this:

public int compareTo(Element that) {
    final int comp = key.compareTo(that.key);
    if (comp < 0)
        return -1;
    else if(comp > 0)
        return 1;
    else
        return 0;
}

Or, better, just return the result of calling compareTo():

public int compareTo(Element that) {
    return key.compareTo(that.key);
}