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

↘锁芯ラ 提交于 2019-12-30 04:31:04

问题


How does Java know which String::compareTo method reference to use when calling Collections.sort(someListOfStrings, String::compareTo);? compareTo is not static and it needs to know the value of the "left hand side" of the comparison.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/32418461/how-does-java-8-know-which-stringcompareto-method-reference-to-use-when-sortin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!