Search code examples
javalambdajava-8functional-interface

FunctionalInterface Comparator has 2 abstract methods


Learning Java 8 Lambdas and just wondering how the compiler knows which method in Comparator to use for the lambda expression? It doesn't seem to be a SAM interface? It has 2 abstract methods:

@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
    boolean equals(Object obj);
}

Solution

  • equals() is not an abstract method. This method overrides Object.equals(Object), and is there only for the Comparator interface to be able to have javadoc attached to the method, explaining how comparators should implement equals().

    See the javadoc of FunctionalInterface:

    If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.