user3397080
user3397080

Reputation: 75

Greater Than Operator Undefined on Generic Type, Despite extending and implementing Comparable

I searched and found several instances of similar problems but the obvious solutions have already been implemented, so I'm at a bit of a loss. FYI: This is a homework assignment, if it matters.

public class Entry<K extends Comparable<K>, V> implements 
    Comparable<Entry<K, V>> {

    protected K key;
    protected V value;

    protected Entry(K k, V v) {
        key = k;
        value = v;
    }

    public K key() {
        return key;
    }

    public V value() {
        return value;
    }

    // override toString method
    // toString method should print the entry as:
    // <key,value>
    @Override
    public String toString() {
        return "<>" + key.toString() + ", " + value.toString();
    }

    public int compareTo(Entry<K, V> other) {
        if (this.key > other.key)
            return 1;
        else if (this.key == other.key)
            return 0;
        else
            return -1;
    }
}

The error that I'm getting is:

The operator > is undefined for the argument type(s) K, K"

in the first line of the compareTo method.

Upvotes: 3

Views: 1226

Answers (2)

Distjubo
Distjubo

Reputation: 1009

Java is not the same as C/C++ where you can override/overload operators. You have to use the method forms.

EDIT: If the types are primitive types like int or float, you can use the < and > operators. But since K is a reference, like the Integer CLASS, you can't.

Upvotes: 3

Mureinik
Mureinik

Reputation: 311798

Java does not support operator overloading - <, >, <= and >= are only defined for primitive numeric types. Instead, since K is a Comparable, you could call its compareTo method:

public int compareTo(Entry<K, V> other) {
    return key.compareTo(other.key);
}

Upvotes: 7

Related Questions