How does implements Comparator work in java?

隐身守侯 提交于 2020-05-14 01:29:08

问题


Java Comparator interface - Here is an example of how Comparator works.

My question is : Where is Object type o1 and o2 coming when the method compare(Object o1,Object o2) ? I don't know see any Class invoke the compare() method. I only see Collections.sort(al,new NameComparator());

Please explain, thank you.


回答1:


When you call Collections.sort on any collection and pass the comparator reference , The underlying sorting method makes a call to compare method to decide which one is greater between two objects. This process happens according to the sorting strategy.

Java code reference: Here is the chaining:

  1. You call Collections.sort(collectionReference, comparatorReference)
  2. the first one internally calls: list.sort(comparatorReference);
  3. list.sort internally converts the list to array and call
    Object[] a = this.toArray(); Arrays.sort(a, (Comparator) comparatorReference);

  4. Arrays.sort has the following logic:

     public static <T> void sort(T[] a, Comparator<? super T> c) {
       if (c == null) {
        sort(a);
       } else {
         if (LegacyMergeSort.userRequested)
            legacyMergeSort(a, c);
         else
            TimSort.sort(a, 0, a.length, c, null, 0, 0);
       }
     }
    
  5. Let's inspect one of the sorting technique if c is not null:legacyMergeSort.

One Snippet which calls compare method:

   if (length < INSERTIONSORT_THRESHOLD) {
    for (int i=low; i<high; i++)
        for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
            swap(dest, j, j-1);
    return;
  }

notice the c.compare method.

It's not good if I post the entire class code here. Please look the classes that i listed and you will find references of where the call to compare method exist which makes comparator logic works in collection sorting.



来源:https://stackoverflow.com/questions/48494211/how-does-implements-comparator-work-in-java

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