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


i know in java collections class, there static method sort:

sort(list<t> list, comparator<? super t> c**) 

the second argument in sort should object implements comparator interface , it's compare method.

but when learn lambda's method reference, see 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 example of method reference instance method. compareword method has nothing comparator interface, can not understand why works? can explain this?

thank much.

int compareword(string a, string b) has same signature int compare(string o1, string o2) method of comparator<string> interface. therefore can used implementation of interface.

this shorter way of writing:

collections.sort(lst, new comparator<string> () {                      public int compare (string o1, string o2) {                          return compareword(o1,o2);                      }                  }); 

in java 8 functional interface such comparator (i.e. interface having single abstract method) can implemented method reference of method having signature matching signature of interface's abstract method.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -