method reference: position of new

Adryr83 :

I know there are four method reference:

  • Class::new

  • Class:: static method

  • instance:: instance method

  • Class :: instance method

In this exercise, I discovered another form of method reference and I want to ask you how it is possible.

class Person{     
    String name;     
    String dob;     
    public Person(String name, String dob){         
        this.name = name; this.dob = dob;     
    } 
} 

class MySorter {     
    public int compare(Person p1, Person p2){         
        return p1.dob.compareTo(p2.dob);     
    } 
} 

public class SortTest {     
    public static int diff(Person p1, Person p2){         
        return p1.dob.compareTo(p2.dob);     
    }          

    public static int diff(Date d1, Date d2){         
        return d1.compareTo(d2);     
    }     

    public static void main(String[] args) {         
        ArrayList<Person> al = new ArrayList<>();         
        al.add(new Person("Paul", "01012000"));         
        al.add(new Person("Peter", "01011990"));         
        al.add(new Person("Patrick", "01012002"));                           
        //INSERT CODE HERE     
    } 
}

In this exercises it is necessary to indicate how many of the above lines can be inserted into the given code, independent of each other, to sort the list referred to by al:

  1. java.util.Collections.sort(al, (p1, p2)->p1.dob.compareTo(p2.dob));
  2. java.util.Collections.sort(al, SortTest::diff);
  3. java.util.Collections.sort(al, new MySorter()::compare);

I thought the correct answers were 1 and 2. But the solution of this exercise indicates as correct all the lines (1, 2 and 3).

How is it possible to create "new Class:staticMethod"?

Thanks a lot!

A.

GBlodgett :

All three versions will work:

  • java.util.Collections.sort(al, (p1, p2)->p1.dob.compareTo(p2.dob));

Is the lambda version of calling SortTest::diff

  • java.util.Collections.sort(al, SortTest::diff);

Will work because it is using a method reference to the static method:

public static int diff(Person p1, Person p2){         
    return p1.dob.compareTo(p2.dob);     
}

And

  • java.util.Collections.sort(al, new MySorter()::compare);

Works because new MySorter() creates an object of type MySorter, and then ::compare passes a method reference to the instance method compare, which is legal

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=146277&siteId=1