比较器必须重写超类方法
我正在制作一个 TreeMap
并希望以降序方式对其进行排序。我创建了以下比较器:
Comparator<String> descender = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
};
我像这样构造了 TreeMap:
myMap = new TreeMap
但是,我收到以下错误:
The method compare(String, String) of type new Comparator<String>(){} must override a superclass 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的 Eclipse 项目显然设置为 Java 1.5。接口方法确实不支持
@Override
注释。删除该注释或将项目的合规性级别修复为 Java 1.6。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.如果您只想反转自然(升序)排序,则无需编写自定义比较器。
要获得降序排列只需使用:
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:
啊,我发现问题了。当实例化 Comparable 的新匿名实例时,我没有重写接口方法......我正在实现它们。 @Override 指令就是问题所在。 Compare() 方法并没有重写现有方法,而是实现了接口的一部分。我从另一个地方复制了该代码,它不应该有@Override。
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.