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); }
Methods From Object Class in Functional Interfaces How is it a functional interface when it has two abstract methods? Because equals() method signature matches from Object, and the compare() method is the only remaining abstract method, hence the Comparator interface is a functional interface.
A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit.
So we can have methods that can have their own body inside the interface one of them being static methods. So from Java 8 onwards it's not 100 % correct to say that interface can only have abstract methods.
This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With