You don't need to cast key or value to comparable since V
is required to be comparable already. Doing so just makes it harder to use your class because now you have just a Comparable
instead of usable values or keys.
public int getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public int compareTo(KeyValPair<V> toComp) {
return -this.getValue().compareTo(toComp.getValue());
}
You should also consider to relax the requirement that V
must implement Comparable<V>
class KeyValPair<V extends Comparable<? super V>>
would allow e.g. classes like Apple extends Fruit implements Comparable<Fruit>
- those can still be ordered if they are comparable to super types.