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

前端 未结 5 1078
一生所求
一生所求 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

    It is a reference to an instance method from some type. In the case of the example, compareToIgnoreCase is a method from String. The program knows that it can invoke this method on an instance of String, so it can take the reference and any object of that type and be guaranteed the method exists.

    I would compare this to the Method class in that they refer to a method and can be invoked on an arbitrary instance of some type.

    For the example, it can use two String objects and call compareToIgnoreCase on one and use the other as an argument to match the method signature. This allows it to take the array and sort it based on any method of the array type instead of requiring a comparator instance to do this instead.

    And here is the example for anyone who didn't click on the link in the question:

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

提交回复
热议问题