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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, think in lambda expression is always clearer than method reference

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.