36

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);
}
Naman
  • 27,789
  • 26
  • 218
  • 353
DarVar
  • 16,882
  • 29
  • 97
  • 146

3 Answers3

55

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    It's a pity that `equals` is listed under the Abstract Methods tab when it's not really an abstract method. – DodgyCodeException Feb 07 '19 at 16:48
  • You are saying `equals` method is overrides but interface or functional interface not a child of Object class. Can you please help me to understand this? – ankit Nov 08 '19 at 12:37
6

equals() is inherited from Object, and inherited public methods are not counted when you’re determining whether an interface is a functional interface. So even though equals() is abstract in Comparator, because it’s inherited, it doesn’t count.

RULE: A functional interface is an interface that has one abstract method. Default methods don’t count; static methods don’t count; and methods inherited from Object don’t count.

Xelian
  • 16,680
  • 25
  • 99
  • 152
1

All classes descend from Object class and Object contains an equal method.
So, this means that every instance that implements Comparator will already have an implementation of equal method.

Therefore Only one method is required to override by the Implanting class of Comparator Interface.
This makes only one abstract method in Comparator interface

This is why Comparator is a functional interface

noetix
  • 4,773
  • 3
  • 26
  • 47
seinta
  • 115
  • 1
  • 6