2
String[] foo = {"one","two", "three"};
Arrays.sort(foo, (a,b) -> a.compareTo(b));

And

String[] foo = {"one","two", "three"};
Arrays.sort(foo, String::compareTo);

are equivalent.

Why can I reference compareTo via String when compareTo is an instance method?

2

1 Answer 1

4

Think of this example

Function<String, String> func;  

func = string -> string.toUpperCase();

func = String::toUpperCase;

Think of an instance method as a static method with an extra this parameter, for the purpose of deducing method reference.

    static String toUpperCase(String this)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.