Collections.sort sort Analysis in Java

sort method in the Collections class implements may be ordered set List interface. This method assumes that the list elements implement the Comparable interface.

View Java official document shows, sort There are two overloaded forms. The first is overloaded:

static <T extends Comparable<? super T>> void sort(List<T> list)

This method will list elements in ascending order , but the list should meet the following criteria:

1. list elements implement the Comparable interface, and a list of any two elements are comparable.
  2. The list must support the set method.

// ascending order
Collections.sort (list);

The method can sort by descending order?

This method requires the use of second overloaded form sort method:

public static <T> void sort(List<T> list,Comparator<? super T> c)

To sort by other means, it may be a Comparator object as the second argument of the sort method. When you want to reverse order, the easiest way is to Collections.reverseOrder () as the second parameter.

// reverse order
Collections.sort (list, Collections.reverseOrder ()) ;

to sum up:

Integer String or 1. For these classes Comparable interface has been achieved, the method can be used directly passed Collections.sort default list of parameters to implement (positive sequence) sorted;

2. If you do not want to use the default mode (positive sequence) sorted by Collections.sort second parameter type is passed from the Comparator define collation;

3. For custom types (e.g., Emp present example), if you want to use a sort Collections.sort manner, can be achieved by a method compareTo Comparable interface, if not achieved, then the reference point 2;

The Comparator interface 4.jdk1.8 There are many new methods, which have the reversed () method is more practical, is used to switch the positive and reverse.

Reference may read: https: //www.cnblogs.com/yw0219/p/7222108.html

Published 254 original articles · won praise 23 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_30242987/article/details/104696484