The collections class can sort the store with the elements in the list, sort by the sort method for the element, or sort by the specified sort class.
The collections class provides two static sort methods:
Sort (list<t> List)
Sort (list<t> List, comparator<? Super T> C)
The first method is to sort the elements in the list directly, and the ordering method requires the elements stored in the list to be provided, that is, if the stored elements are sortable;
The second method, in addition to providing a list to sort, also needs to provide a specified sort class to specify the collation, and the elements stored in the list do not implement a sortable interface.
View their specific implementations from the source code:
Public static <t extends comparable<? super t>> void sort ( list<t> list) { object[] a = list.toarray (); arrays.sort (a); listiterator<t> i = list.listiterator ( ); for (int j=0; j<a.length; j++) { i.next (); i.set ((T) a[j]); }}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++) { &nbsP; i.next (); i.set (A[j]); }}
The two sort methods of the
collections call the two corresponding sort methods of arrays, and push the implementation of the sort to arrays, let's see how the Sort method is implemented in arrays:
public static void sort (Object[] a) { Object[] aux = (object[]) A.clone (); mergesort (aux, a, 0, a.length, 0); } private static void mergesort (object[] src, Object[] dest, int low, int high, int off) { int length = high - low; // insertion sort on smallest arrays if (Length < insertionsort_threshold) { for (int i=low; iThe
Arrays.sort method without the comparer parameter calls the MergeSort method without the comparer, and the CompareTo method that stores the object itself is called in the implementation of the MergeSort, so the object that uses this method to sort sorts must implement the CompareTo method.
public static <t> void sort (T[] &NBSP;A,&NBSP;COMPARATOR<?&NBSP;SUPER&NBSP;T>&NBSP;C) { T[] aux = (t[]) A.clone (); if (c==null ) mergesort (aux, a, 0, a.length, 0); else mergesort (aux, a, 0, a.length, 0, c); } private static void mergesort ( object[] src, Object[] dest, int low, int high, int off, &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;COMPARATOR&NBSP;C) { int length = high - low; // Insertion sort on smallest arrays if (Length < insertionsort_threshold) { for (int i=low; iThe Arrays.sort method with the comparator parameter calls the MergeSort method with the comparator, and the CompareTo method of the comparer is called in the implementation of MergeSort, without invoking the storage object itself. You only need to specify a comparer.
Java records -67-in-depth anatomy of the collections Sort method