我有這樣的類名稱對沒有合適的方法:錯誤的Collections.sort:發現排序
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;
}
}
在Program類
我有這樣的方法:
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);
}
該行:
Collections.sort(vector);
我得到這個錯誤:
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))
我實現了Comparable接口。爲什麼我會收到上面的錯誤?
@Andy請解釋。 – Michael
問題是它本身沒有可比性。 – shmosel
@shmosel我需要在我的代碼中更改什麼? – Michael