Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); } 
like image 347
DarVar Avatar asked May 18 '14 12:05

DarVar


People also ask

Why Comparator has two abstract methods?

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.

Can we have 2 abstract methods in functional interface?

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit.

CAN interface have multiple abstract methods?

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.

What methods are in the Comparator interface?

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.


1 Answers

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.

like image 156
JB Nizet Avatar answered Oct 02 '22 15:10

JB Nizet