I. array sorting (Arrays. sort)
When we encounter array sorting, we often use several sort methods we have learned, while java provides Arrays. sort directly uses Arrays when there are few data elements or the efficiency requirement is not high. sort is easier. After checking the source code, Arrays. sort uses quick sorting.
1. Number sorting int [] intArray = new int [] {4, 1, 3,-23 };
Arrays. sort (intArray );
Output: [-23, 1, 3, 4]
2. Sort strings in upper case and lower case String [] strArray = new String [] {"z", "a", "C "};
Arrays. sort (strArray );
Output: [C, a, z]
3. Strictly sort by alphabet, that is, ignore Case-insensitive sort
Arrays. sort (strArray, String. CASE_INSENSITIVE_ORDER );
Output: [a, C, z]
4. Reverse sorting, Reverse-order sort
Arrays. sort (strArray, Collections. reverseOrder ());
Output: [z, a, C]
5. Ignore Case-insensitive reverse sorting Case-insensitive reverse-order sort
Arrays. sort (strArray, String. CASE_INSENSITIVE_ORDER );
Collections. reverse (Arrays. asList (strArray ));
Output: [z, C, a]
6. Sort object arrays
To sort an array of objects, you must implement the java. util. Comparator interface by yourself.
Example:
Common_User [] userListTemp = new Common_User [temp. size ()];
Arrays. sort (userListTemp, new PinyinComparator ());
PinyinComparator implements the Comparator interface and overwrites the compare method to tell Arrays to compare the size of two objects according to what rules.
For more information about Comparator examples, see the following section.
Ii. Set sorting (Collections. sort)
To sort a set, you must implement the java. util. Comparator interface by yourself.
List Temp = (List ) Ar. list;
Collections. sort (temp, new Comparator (){
Public int compare (WBMessage arg0, WBMessage arg1 ){
// Ascending Order: arg0.compareTo (arg1) If arg0 is smaller than arg1, a negative value is returned.
// Descending order: arg1.compareTo (arg0)
String B = arg1.getTime ();
String a = arg0.getTime ();
Return B. compareTo ();
}
});