问题
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:
- You call Collections.sort(collectionReference, comparatorReference)
- the first one internally calls: list.sort(comparatorReference);
list.sort internally converts the list to array and call
Object[] a = this.toArray(); Arrays.sort(a, (Comparator) comparatorReference);
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); } }
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