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

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

    Please see the below code sample which explains "Reference to an Instance Method of an Arbitrary Object of a Particular Type" category described in https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

    import java.util.Arrays;
    
    class Person{
    String name;
    
    //constructor
    public Person(String name){
        this.name = name;
    }
    
    //instance method 1
    public int personInstanceMethod1(Person person){
        return this.name.compareTo(person.name);
    }
    
    //instance method 2
    public int personInstanceMethod2(Person person1, Person person2){
        return person1.name.compareTo(person2.name);
    }
    }
    
    class Test {
    public static void main (String[] args) throws Exception{
        Person[] personArray = {new Person("A"), new Person("B")};
    
        // Scenario 1 : Getting compiled successfully
        Arrays.sort(personArray, Person::personInstanceMethod1);
    
        // Scenario 2 : Compile failure
        Arrays.sort(personArray, Person::personInstanceMethod2);
    
        // Scenario 3 : Getting compiled successfully. 
        Person personInstance = new Person("C");
        Arrays.sort(personArray, personInstance::personInstanceMethod2);
    
        // Scenario 4 : Getting compiled successfully. As the same way as "Scenario 1"
        String[] stringArray = { "Barbara", "James", "Mary", "John",
                "Patricia", "Robert", "Michael", "Linda" };
        Arrays.sort(stringArray, String::compareToIgnoreCase);
    }
    
    }
    

    Scenario 1 and Scenario 4 describes "Reference to an Instance Method of an Arbitrary Object of a Particular Type" category described in https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

    If the method parameter takes a variable in same instance Type as the instance Type of the element, you can call that instance method using Type.(Person::personInstanceMethod1)

    Compare "personInstanceMethod1" instance method in "Person" class with "compareToIgnoreCase" instance method in "String" class (https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#compareToIgnoreCase-java.lang.String-) to see the similarity. Both are taking a single parameter with the same Type.

    Compare Scenario 1 and Scenario 2 to see the difference.

提交回复
热议问题