尝试使用Comparator时出错

时间:2015-04-30 15:53:20

标签: java

我不知道我做错了什么,但当我尝试将public final Comparator<K> cmp初始化为某个值时,我收到错误。

public class FastGetListMM<K,V> extends AbstractListMM<K,V> {

    // Comparator used to sort elements; may be null if elements are Comparable
    public final Comparator<K> cmp;    
    private List<K> keys;;
    private List<V> values;

    // Assume elements must be comparable
    public FastGetListMM(ArrayList<K> keys, ArrayList<V> values)
    {
        super(keys, values);
        //this.cmp = new Comparator<K>(); <<----error
    }

    // Use the given comparator to sort the keys
    public FastGetListMM(Comparator<K> cmp)
    {
        super(cmp); <<-----error
        //this.cmp = cmp;  <<----error
    }

1 个答案:

答案 0 :(得分:4)

由此:

this.cmp = new Comparator<K>(); 

您尝试直接实例化interface,这是不允许的。您必须首先创建实现Comparator<K>的类,或实例化匿名类,如:

this.cmp = new Comparator<K>(){
    @Override
    public int compare(K k1, K k2) {
        // compare k1 and k2 here
    }
}

或指定一个lambda,如:

Comparator<K> cmp = (k1, k2) -> { /* compare k1 to k2 */ };

如果您更喜欢课程,请使用以下习语:

public static class MyComparator<K> implements Comparator<K> {
    @Override
    public int compare(K k1, K k2) {
        // compare k1 to k2
    }
}

然后,在外部代码中实例化这个类:

Comparator<K> cmp = new MyComparator<>();