[英]Comparator<String> must override super class method
I'm making a TreeMap<String, String>
and want to order it in a descending fashion. 我正在制作一个TreeMap<String, String>
并希望以降序排序。 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: 我像这样构造TreeMap:
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? 我从未完全弄清楚仿制药,我做错了什么?
Your Eclipse project is apparently set to Java 1.5. 您的Eclipse项目显然已设置为Java 1.5。 The @Override
annotation is then indeed not supported on interface methods. 然后,接口方法确实不支持@Override
注释。 Either remove that annotation or fix your project's compliance level to Java 1.6. 删除该批注或将项目的合规性级别修复为Java 1.6。
You don't need to write a custom Comparator
if 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());
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. 在实例化Comparable的新匿名实例时,我没有覆盖接口方法......我正在实现它们。 The @Override directive was the problem. @Override指令是问题所在。 The compare() method wasn't overriding an existing method, it was implementing part of the interface. compare()方法没有覆盖现有方法,它正在实现接口的一部分。 I copied that code from another place and it shouldn't have had the @Override. 我从其他地方复制了该代码,它不应该有@Override。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.