2017-07-13 21 views
1

我有這樣的類名稱對沒有合適的方法:錯誤的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接口。爲什麼我會收到上面的錯誤?

+0

@Andy請解釋。 – Michael

+3

問題是它本身沒有可比性。 – shmosel

+0

@shmosel我需要在我的代碼中更改什麼? – Michael

回答

4

你的類必須實現的Comparable<Pair<K,V>>代替Comparable<V>

想想看,你正試圖排序Pair<K,V>對象的列表。爲了使Collections庫知道如何對它進行排序,它必須知道一個Pair<K,V>對象是否小於,大於或等於另一個Pair<K,V>對象。

你,而不是描述的比較操作比較Pair<K,V>V

+1

絕對物流+1 – Michael

+0

@Michael請接受它,如果解決了問題 –