Search code examples
javamethod-reference

Method reference to an instance method of an arbitrary object of a particular type


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".....)

Solution

  • "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