Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java 8 know which String::compareTo method reference to use when sorting?

How does Java know which String::compareTo method reference to use when calling Collections.sort(someListOfStrings, String::compareTo);? compareTo is not static and it needs to know the value of the "left hand side" of the comparison.

like image 804
stantonk Avatar asked Sep 05 '15 22:09

stantonk


1 Answers

Suppose that you use method reference for Comparator interface:

Comparator<String> cmp = String::compareTo;

When you call the cmp.compare(left, right) (which is "single abstract method" or "SAM" of Comparator interface), the magic occurs:

int result = cmp.compare(left, right);
                           |     |
  /------------------------/     |
  |              /---------------/
  |              |
left.compareTo(right);

Basically all the parameters of SAM are converted to the parameters of the referred method, but this object (which is on the left side) is also counted as parameter.

like image 191
Tagir Valeev Avatar answered Jun 24 '23 23:06

Tagir Valeev