I tried reproducing the code below on eclipse. I get an error telling me that I have to implement all the inherited methods (because Comparator is an interface).
The type
new Comparator(){}
must implement the inherited abstract methodComparator.reversed()
.
There are many of these methods and the only one I want to overwrite is compare. Do I have to implement all the other methods or is there a way to specify I don't need to implement them? I understand that I will have to do it because of the contractual nature of an interface, but what if I just need to change one method?
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;
}
EDIT Solved by changing the compliance level to java8 in eclipse luna. Thanks!
The purpose of an interface is to obligate the implementer of said interface to have all of the methods listed there. Now there are a few ways to got about not implementing all of the methods.
Comparator.reversed
was introduced in Java 1.8 and it's a default method i.e. a method that you don't have to override.It seems like you have your compliance level set to pre Java 1.8 (since Eclipse asks you to override
reversed
), while using Java 1.8 API (sinceComparator
has areversed
method).Make sure you either change your API to 1.7 or change your compliance level to 1.8. (The latter option requires Eclipse Luna or better.)
More on Eclipse compliance level: What is "compiler compliance level" in Eclipse?
This is sort of a wild guess: I think you are using Java 8 in a pre-Java 8-Eclipse (i.e. pre-Luna). This way, Eclipse does not know that all those new Comparator methods, like
thenComparing
, have a default implementation.In Java 7, Comparator has just the method
compare
, while in Java 8 in has a whole lot more methods, all of which have a default implementation directly in the interface and need not to be implemented in a subclass.I suggest you switch to the newest version of Eclipse, which should be Luna. Alternatively, you can also install a patch for Eclipse Kepler, but switching to Luna is certainly better.
An abstract class may be better suited for what you are doing. Although you could just
.super()
everything.You have run into an Eclipse bug: https://bugs.eclipse.org/bugs/show_bug.cgi?id=390889
Basically, JAVA 1.8 introduced a brand new method Comparator.reversed(). And since you have a JAVA 1.7 or earlier code, JAVA 1.8 doesn't find the method and fails to compile.