9

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?

Kenny Wyland
  • 20,844
  • 26
  • 117
  • 229
  • 1
    As far as I can see, nothing. The error would be caused if your compare method didn't match the signature of Comparator's compare() method, but that doesn't seem to be the case as far as I can see. – cthulhu Aug 28 '11 at 20:02

3 Answers3

19

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • And here is a link showing you how to reset project jre version https://stackoverflow.com/questions/20145797/eclipse-jre-system-library-in-java-build-path-reset – Mark Jin May 25 '18 at 14:25
7

You don't need to write a custom Comparator if you just want to reverse the natural (ascending) ordering.

To get a descending ordering just use:

myMap = new TreeMap<String, String>(java.util.Collections.reverseOrder());
Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65
1

Ah, I found the problem. When instantiating a new anonymous instance of a Comparable, I'm not overriding the interfaces methods... I'm implementing them. The @Override directive was the problem. The compare() method wasn't overriding an existing method, it was implementing part of the interface. I copied that code from another place and it shouldn't have had the @Override.

Kenny Wyland
  • 20,844
  • 26
  • 117
  • 229
  • 3
    Your project is probably set to 1.5 source level. Since 1.6 you are allowed to annotate methods specified by an interface with `@Override`, too. – Philipp Reichart Aug 28 '11 at 20:16