Reputation: 13636
I have this class called Pair:
public class Pair<K,V> implements Map.Entry<K,V> , Comparable<Pair<K,V>>{
private K key;
private V value;
public Pair(){}
public Pair(K _key, V _value){
key = _key;
value = _value;
}
//---Map.Entry interface methods implementation
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V _value) {
return value = _value;
}
///---Map.Entry interface methods implementation
@Override
// if return value negative passed value is bigger
// if return value positive passed value is smaller
// if return value is zero values is equal
public int compareTo(Pair<K, V> o) {
V val1 = o.getValue();
V val2 = this.getValue();
// how to make compare between values(to check if val1 is bigger or equal to val2 and vice versa )
}
}
As you can see class Pair
contains Key
and Value
properties.I need to compare between the value properties and return int value according to result of the comparison.
In class I try to implement compareTo
method.But I don't know to to compare generic values.
How can I implement comparison of values in compare to method?
Upvotes: 2
Views: 60
Reputation: 10396
You can use compareTo
of V
, as long as V
implements Comparable
interface, relying the comparison to the classe which will be used as value of the Pair
:
public int compareTo(Pair<K, V> o) {
V val1 = o.getValue();
V val2 = this.getValue();
return val1.compareTo(val2);
}
Upvotes: 1
Reputation: 124804
To be able to compare V
,
it needs to be comparable.
Change the declaration of Pair
to make it so with this added constraint on V
, like this:
class Pair<K, V extends Comparable<V>> implements Map.Entry<K, V>, Comparable<Pair<K, V>> {
And then you will be able to write compareTo
like this:
public int compareTo(Pair<K, V> o) {
V val1 = o.getValue();
V val2 = this.getValue();
return val1.compareTo(val2);
}
To explain a bit more... In this declaration, we don't know anything at all about T
:
class Item<T> {
Since we don't know anything about it, values of type T
within this class only have the methods of Object
, nothing else.
If you write like this, we add information about T
:
class Item<T extends Comparable<T>> {
Here we know that T
extends Comparable<T>
,
so values of type T
within this class have the methods of Comparable<T>
,
that is compareTo(T other)
.
Upvotes: 6