0

I do not know what I'm doing wrong but when I try initialize public final Comparator<K> cmp to a value, I get an error.

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
    }
6
  • What error are you getting? Commented Apr 30, 2015 at 15:54
  • Does your AbstractListMM class has an comparator? Commented Apr 30, 2015 at 15:54
  • 1
    Comparator is interface, you cannot instantiate it by new directly. Or you need to instantiate anonymous class for it. Commented Apr 30, 2015 at 15:55
  • @Razib, no it does not have. Commented Apr 30, 2015 at 15:56
  • @SMcCrohan Cannot instantiate the type Comparator<K> Commented Apr 30, 2015 at 15:57

1 Answer 1

5

By this:

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

you try to instantiate interface directly, which is not allowed. You must first to create class implementing Comparator<K>, or instantiate anonymous class, like:

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

or assign a lambda, like:

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

If you prefer classes, use following idiom:

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

Then, in outer code instantiate this class:

Comparator<K> cmp = new MyComparator<>();
Sign up to request clarification or add additional context in comments.

7 Comments

@TNT That's what I get for rushing! I'm going to shush and go home.
I tried that, @SashaSalauyou, what whatever I try i get this Cannot instantiate the type Comparator<K>. Is there something I need to do? Should I put implements Comparator in the name of the class?
The lambda expression will throw an error since it is unknown whether the type of K implements java.lang.Comparable. In order for it to work MyComparator<K> would have to be MyComparator<K extends Comparable<? super K>>.
@TNT it was just for example. If you compare hashcodes (for example), type of K can be unbounded.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.