1
String[] arr = {"First", "Second", "Third", "Fourth"};
Arrays.sort(arr, String::compareToIgnoreCase); //can compile
Arrays.sort(arr, "a"::compareToIgnoreCase); //can't compile
  1. why the "a"::compareToIgnoreCase cannot compile? if we can said String::compareToIgnoreCase has an implicit String argument (this), why we cannot said "a"::compareToIgnoreCase has an implicit "a" as argument? ("a" compare to "First", "a" compare to "Second".....)
user1169587
  • 1,104
  • 2
  • 17
  • 34

1 Answers1

2

"a"::compareToIgnoreCase is a method reference to a method of a single argument, which compares a given String to the String "a". The implicit argument is always equal to "a".

A Comparator's Compare method requires two given String instances.

Maybe if you write the method references as lambda expressions it would be clearer:

Arrays.sort(arr, (a,b) -> a.compareToIgnoreCase(b)); //can compile

Arrays.sort(arr, (x) -> "a".compareToIgnoreCase(x)); // can't compile, since a method with 
                                                     // two arguments is expected
Eran
  • 387,369
  • 54
  • 702
  • 768