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

前端 未结 5 1075
一生所求
一生所求 2020-11-29 06:29

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.oracl

5条回答
  •  野性不改
    2020-11-29 07:03

    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/

提交回复
热议问题