Reputation: 75
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
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
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