Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, why collections.sort() still works with non-comparator typed argument?

I know in java Collections class, there is a static method sort:

sort(List<T> list, Comparator<? super T> c**)

The second argument in sort should be an object which implements Comparator interface and it's compare method.

But when I learn lambda's method reference, I see this example:

public class Test 
{
     public static void main(String[] args) 
    {
        new Test().sortWord();  
    }

    public void sortWord()
    {
        List<String> lst = new ArrayList<>();
        lst.add("hello");
        lst.add("world");
        lst.add("apple");
        lst.add("zipcode");

        Collections.sort(lst, this::compareWord);

        System.out.println(lst);
    }

    public int compareWord(String a, String b)
    {
       return a.compareTo(b);
    }

}

This is an example of method reference for instance method. the compareWord method has nothing to do with the Comparator interface, I can not understand why this works? can anyone explain this?

Thank you very much.

like image 760
chengdol Avatar asked Aug 20 '17 06:08

chengdol


Video Answer


1 Answers

int compareWord(String a, String b) has the same signature as the int compare(String o1, String o2) method of the Comparator<String> interface. Therefore it can be used as an implementation of that interface.

This is a shorter way of writing:

Collections.sort(lst, new Comparator<String> () {
                     public int compare (String o1, String o2) {
                         return compareWord(o1,o2);
                     }
                 });

In Java 8 any functional interface such as Comparator (i.e. interface having a single abstract method) can be implemented with a method reference of a method having a signature matching the signature of that interface's abstract method.

like image 91
Eran Avatar answered Sep 28 '22 09:09

Eran