Collections.sort出错:找不到合适的排序方法

时间:2017-07-13 21:11:29

标签: java sorting

我有这个班级名字对:

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;
    }
}
程序类中的

我有这个方法:

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接口。为什么我会得到上面的错误?

1 个答案:

答案 0 :(得分:4)

您的班级必须实施Comparable<Pair<K,V>>而不是Comparable<V>

考虑一下,您正在尝试对Pair<K,V>个对象进行排序。要使Collections库知道如何对其进行排序,它必须知道一个Pair<K,V>对象是否小于,大于或等于另一个Pair<K,V>对象。

您已经描述了将Pair<K,V>V

进行比较的比较操作
相关问题