java Comparator<String> 必须覆盖超类方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7223512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:10:36  来源:igfitidea点击:

Comparator<String> must override super class method

javagenericsmapcomparatortreemap

提问by Kenny Wyland

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

我正在制作一个TreeMap<String, String>并希望以降序方式订购它。我创建了以下比较器:

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

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

I construct the TreeMap like so:

我像这样构造 TreeMap:

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

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?

我从来没有完全理解泛型,我做错了什么?

回答by BalusC

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

您的 Eclipse 项目显然设置为 Java 1.5。@Override接口方法确实不支持该注释。删除该注释或将项目的合规性级别修复为 Java 1.6。

回答by Philipp Reichart

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

Comparator如果您只想反转自然(升序)排序,则无需编写自定义。

To get a descending ordering just use:

要获得降序,只需使用:

myMap = new TreeMap<String, String>(java.util.Collections.reverseOrder());

回答by Kenny Wyland

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.

啊,我发现问题了。在实例化 Comparable 的新匿名实例时,我没有覆盖接口方法......我正在实现它们。@Override 指令是问题所在。compare() 方法没有覆盖现有方法,它实现了接口的一部分。我从另一个地方复制了那个代码,它不应该有@Override。