What does "an Arbitrary Object of a Particular Type" mean in java 8?

Roman Ivanov picture Roman Ivanov · May 8, 2014 · Viewed 12k times · Source

In Java 8 there is "Method Reference" feature. One of its kind is "Reference to an instance method of an arbitrary object of a particular type"

http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html#type

Can someone explain what does "arbitrary object of particular type" mean in that context ?

Answer

Jawad picture Jawad · Sep 3, 2014

The example given from the Oracle Doc linked is:

String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);

The lambda equivalent of

 String::compareToIgnoreCase

would be

(String a, String b) -> a.compareToIgnoreCase(b)

The Arrays.sort() method is looking for a comparator as its second argument (in this example). Passing String::compareToIgnoreCase creates a comparator with a.compareToIgnoreCase(b) as the compare method's body. You then ask well what's a and b. The first argument for the compare method becomes a and the second b. Those are the arbitrary objects, of the type String (the particular type).

Don't understand?

  • Make sure you know what a comparator is and how to implement it.
  • Know what a functional interface is and how it affects lambdas in Java.
  • A comparator is a functional interface that's why the method reference becomes the body of the compare method inside the comparator object.
  • Read the source below for another example at the bottom of the page.

Read more at the source: http://moandjiezana.com/blog/2014/understanding-method-references/