我尝试重现代码 below在 eclipse 。我收到一条错误消息,告诉我必须实现所有继承的方法(因为 Comparator 是一个接口(interface))。
The type
new Comparator(){}
must implement the inherited abstract methodComparator.reversed()
.
有很多这样的方法,我唯一想覆盖的是比较。我是否必须实现所有其他方法,或者是否有一种方法可以指定我不需要实现它们? 我 understand由于接口(interface)的契约性质,我将不得不这样做,但如果我只需要更改一种方法怎么办?
static Map sortByValue(Map map) {
List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
Map result = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}
编辑 通过在 eclipse luna 中将合规级别更改为 java8 来解决。谢谢!
最佳答案
The type
new Comparator(){}
must implement the inherited abstract methodComparator.reversed()
then if I apply the fix, I have many functions added
Comparator.reversed
是在 Java 1.8 中引入的,它是一个 default method。即,您不必覆盖的方法。
您似乎将合规级别设置为 Java 1.8 之前的版本(因为 Eclipse 要求您覆盖 reversed
),同时使用 Java 1.8 API(因为 Comparator
有一个反转
方法)。
确保您将 API 更改为 1.7 或将合规级别更改为 1.8。 (后一种选择需要 Eclipse Luna 或更好的软件。)
有关 Eclipse 合规性级别的更多信息: What is "compiler compliance level" in Eclipse?
关于java - 没有实现接口(interface)的所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28203243/