Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator<String> must override super class method

I'm making a TreeMap<String, String> and want to order it in a descending fashion. I created the following comparator:

Comparator<String> descender = new Comparator<String>() {

    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }
};

I construct the TreeMap like so:

myMap = new TreeMap<String, String>(descender);

However, I'm getting the following error:

The method compare(String, String) of type new Comparator<String>(){} must override a superclass method

I've never fully groked generics, what am I doing wrong?

like image 246
Kenny Wyland Avatar asked Aug 28 '11 19:08

Kenny Wyland


People also ask

Which of the given method must be overridden by a class after implementing comparator?

The comparable interface has a method 'compareTo ()' that needs to be overridden in the class implementing the Comparator interface and whose objects are to be sorted. The Comparator interface is used to sort custom objects that are to be sorted based on any other order.

Why we need to Override compareTo method in Java?

In order to change the sorting of the objects according to the need of operation first, we have to implement a Comparable interface in the class and override the compareTo() method.

What methods are in the comparator interface?

This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else.


1 Answers

Your Eclipse project is apparently set to Java 1.5. The @Override annotation is then indeed not supported on interface methods. Either remove that annotation or fix your project's compliance level to Java 1.6.

like image 68
BalusC Avatar answered Sep 18 '22 11:09

BalusC