Comparator<String> must override super class method

不打扰是莪最后的温柔 提交于 2019-12-06 21:16:19

问题


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?


回答1:


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.




回答2:


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());



回答3:


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.



来源:https://stackoverflow.com/questions/7223512/comparatorstring-must-override-super-class-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!