Reputation: 39
I was reading the Java tutorial and saw this line of code:
Comparator<Integer> normal = Integer::compare;
About the right hand side, I tried looking for documentation which explains how compare returns a Comparator for an Integer object. But I found none. The Java API docs show the following:
public static int compare(int x, int y)
What am I missing?
Upvotes: 1
Views: 1786
Reputation: 645
Integer class implements only Comparable
interface.
The compare
method in Integer class is NOT Comparator's
compare
method Implementation. compare
is a static helper method in Integer class itself.
Even before Java 8 we have compare
method in Integer
class. Integer class has two methods in this context one is
public static compare(Integer val1,Integer val2)
another
public int compareTo(Integer val)
. //Comparable Interface Implementation
Therefore, If you invoke compare
method of Integer
class it internally still invoke the impmentation of compareTo
Method of the Comparable
interface defined in the Integer class as below.
public static int compare(int x, int y) {
Integer.valueOf(x).compareTo(Integer.valueOf(y));
}
Upvotes: 0
Reputation: 13923
Comparator<T>
is a functional interface with the signature int compare(T o1, T o2);
. From the documentation of java.util.function: "Functional interfaces provide target types for lambda expressions and method references."
The method Integer#compare(int x, int y)
matches this signature. Its method reference can therefore be assigned to a variable of type Comparator<Integer>
.
To better understand this, I suggest that you read about lambda expressions, method references and functional interfaces.
Upvotes: 3