How does Java 8 know which String::compareTo method reference to use when sorting?

后端 未结 2 1343
北恋
北恋 2021-01-02 10:05

How does Java know which String::compareTo method reference to use when calling Collections.sort(someListOfStrings, String::compareTo);? comp

相关标签:
2条回答
  • 2021-01-02 10:17

    Suppose that you use method reference for Comparator interface:

    Comparator<String> cmp = String::compareTo;
    

    When you call the cmp.compare(left, right) (which is "single abstract method" or "SAM" of Comparator interface), the magic occurs:

    int result = cmp.compare(left, right);
                               |     |
      /------------------------/     |
      |              /---------------/
      |              |
    left.compareTo(right);
    

    Basically all the parameters of SAM are converted to the parameters of the referred method, but this object (which is on the left side) is also counted as parameter.

    0 讨论(0)
  • 2021-01-02 10:23

    OK, the source of Collections.sort() looks as follows:

    public static <T> void sort(List<T> list, Comparator<? super T> c) {
       Object[] a = list.toArray();
       Arrays.sort(a, (Comparator)c);
       ListIterator i = list.listIterator();
       for (int j=0; j<a.length; j++) {
          i.next();
          i.set(a[j]);
       }
    }
    

    I think it is quite clear now. The contents is a list. It means it has an order and the items are treated one by one in that order.

    0 讨论(0)
提交回复
热议问题