Source code analysis - Collections.sort ()
A, Collection.sort use
Collections.sort (): the method is a set of positive sort of first set of element types of incoming Collections.sort () to inherit Comparator <T>, so as to ensure you can compare and sort.
According to source code analysis, there are two main ways to achieve:
(1) Sorting of conventional type and other types String
(2) for a JavaBean properties (such as time, price, age sort) to sort
Use Cases:
List<String> listOne = Arrays.asList("3", "2", "5", "8"); The Collections.sort (in listOne); // default ascending System.out.println ( "in listOne =" + in listOne); /** * Output: * listOne = [2, 3, 5, 8] */
Two, Collections.sort of javabean sort of list
The underlying algorithm is actually converted into a set of Array, then execute arrays.sort, arrays.sort use merge sort, quick drain optimization, timSort like.
2, the data sort string type
String analysis of source code;
Because String type implements Comparable <String> interfaces, can be used Collections.sort (unSorted) sorting;
List<String> unSorted = new ArrayList<String>(); Collections.sort (UNSORTED); // String implements Comparable interface
Note: Due to custom javabean not implemented, it is not directly used, but a comparator may be implemented:
method one:
Collections.sort(unSorted,new Comparator<unSortedBean>() { @Override public int compare(unSortedBean arg0, unSortedBean arg1) { // 升叙 return arg0.getOrder()-arg1.getOrder(); } });
Second way :
Can also be used Collections.sort (); mode, only javabean implement the interface and to achieve comparable ascending or descending order by the compareTo () method;