Reputation: 13636
I have this class name Pair:
public class Pair<K,V> implements Map.Entry<K,V> , Comparable<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
public int compareTo(V o) {
return 0;
}
}
in Program class I have this method:
private static <K,V> void MinMax2(Vector<Pair<K,V>> vector) {
// Collections.sort() sorts the collection in ascending order
Iterator iterator = vector.iterator();
Collections.sort(vector);
}
on this row:
Collections.sort(vector);
I get this error:
Error:(41, 20) java: no suitable method found for sort(java.util.Vector<Pair<K,V>>)
method java.util.Collections.<T>sort(java.util.List<T>) is not applicable
(inference variable T has incompatible bounds
equality constraints: Pair<K,V>
upper bounds: V,java.lang.Comparable<? super T>)
method java.util.Collections.<T>sort(java.util.List<T>,java.util.Comparator<? super T>) is not applicable
(cannot infer type-variable(s) T
(actual and formal argument lists differ in length))
I implemented Comparable interface. Why do I get the error above?
Upvotes: 1
Views: 2521
Reputation: 17568
Your class must implement Comparable<Pair<K,V>>
instead of Comparable<V>
Think about it, you are trying to sort a list of Pair<K,V>
objects. For the Collections library to know how to sort it, it must know whether one Pair<K,V>
object is less than, greater than, or equal to another Pair<K,V>
object.
You have instead described a comparison operation for comparing Pair<K,V>
to V
Upvotes: 4