This blog is mainly from 51CTO blog: http://developer.51cto.com/art/201204/332100.htm
There are several errors in the original article. This article was revised by the experiment!
According to the Conventions, the existing class libraries should be used whenever possible during java programming.Of course, you can also write a sorting method or framework by yourself, but how many people can write better than those in JDK? Another advantage of using existing classes is that the Code is easy to read and maintain. This article mainly describes how to sort arrays and Collection containers using existing class libraries, (some examples in this article are from Java Developers Almanac 1.4.)
First, you need to know two classes: java. util. Arrays and java. util. Collections (note and the Collection area)Collection is the top-level interface of the Collection framework, while Collections contains many static methods. We use Arrays to sort Arrays and Collections to sort containers in combination with frameworks, such as ArraysList and sort list.
In this example, we need to add import java. util. * and other shell code, such as the class and static main method. I will write all the code in the first example, which will be omitted without exception.
Sort Arrays
For example, there is an integer array:
- Int [] intArray = new int [] {4, 1, 3,-23 };
How do we sort data? Are you thinking about a fast sorting algorithm at this time? Let's take a look at the following implementation methods:
- Import java. util .*;
- Public class Sort {
- Public static void main (String [] args ){
- Int [] intArray = new int [] {4, 1, 3,-23 };
- Arrays. sort (intArray );
- }
- }
In this way, we use the static method sort () of Arrays to sort intArray in ascending order. Now the array has become {-23,1, 3,4 }.
If it is a character array:
- String [] strArray = new String [] {"z", "a", "C "};
We use:
- Arrays. sort (strArray );
The sorting result is {C, a, z}
After sorting, {C, a, z}, and sort () are sorted in ascending order based on the natural order of the elements. If you want to be case insensitive, write as follows:
- Arrays. sort (strArray, String. CASE_INSENSITIVE_ORDER );
Of course, we can also specify a part of the array for sorting. For example, we want to sort the part 0-2 of the array table (assuming the array length is greater than 3), and the other part remains unchanged. We can use:
- Arrays. sort (strArray, 0, 3 );
Note:
| |
sort(double[] a, int fromIndex, int toIndex)
-
Parameters:
-
a-Array to be sorted.
-
fromIndex-Index (including) of the first element to be sorted ).
-
toIndex-Index of the last element to be sorted (not included ).
|
In this way, we only sort the first three elements without affecting the subsequent parts. The result is {1, 3, 4,-23 }.
Of course, some people may think, how do I sort in descending order? One of the many sort Methods
- Sort (T [] a, Comparator <? Super T> c)
We can use Comparator to obtain a reverse Comparator. Comparator will explain it later. The previous intArray [] is used as an example:
1 public class Sort { 2 public static void main(String[] args) { 3 Integer[] intArray = {4, 1, 3, -23}; 4 Arrays.sort(intArray, new Comparator<Integer>() { 5 public int compare(Integer o1, Integer o2) { 6 return o2-o1; 7 } 8 }); 9 System.out.println(Arrays.toString(intArray));10 }11 }
In this way, the result is {4, 3, 1,-23 }. If you do not want to modify the original code, you can also use:
- Collections. reverse (Arrays. asList (intArray ));
1 public class Sort {2 public static void main(String[] args) {3 Integer[] intArray = {4, 1, 3, -23};4 Arrays.sort(intArray);5 Collections.reverse(Arrays.asList(intArray));6 System.out.println(Arrays.toString(intArray));7 }8 }
Returns the reverse order of the array. The result is {4, 3, 1,-23 }.
The current situation has changed. Our array is no longer an array of the basic data type (primtive type) or String type, but an array of objects. The natural order of this array is unknown, so we need to implement the Comparable interface for this class. For example, we have a Name class:
1 class Name implements Comparable <Name> {2 public String firstName, lastName; 3 public Name (String firstName, String lastName) {4 this. firstName = firstName; 5 this. lastName = lastName; 6} 7 // implement interface 8 public int compareTo (Name o) {9 int lastCmp = lastName. compareTo (o. lastName); 10 return (lastCmp! = 0? LastCmp: firstName. compareTo (o. firstName); 11} 12 // easy output test 13 public String toString () {14 return firstName + "" + lastName; 15} 16}
In this way, when we sort this object array, we will first compare the lastName, then compare the firstName, and then get the order of the two objects, just like compareTo (Name o). Try it with a program:
1 public class NameSort { 2 public static void main(String[] args) { 3 Name nameArray[] = { 4 new Name("John", "Lennon"), 5 new Name("Karl", "Marx"), 6 new Name("Groucho", "Marx"), 7 new Name("Oscar", "Grouch") 8 }; 9 Arrays.sort(nameArray); 10 System.out.println(Arrays.toString(nameArray));; 11 } 12 }
The result is as expected: [Oscar Grouch, John Lennon, Groucho Marx, Karl Marx]
Sort the collection framework
If Arrays. sort () is understood to sort Arrays, the use of the Collection framework is similar. Only replace Arrays with Collections. Note that Collections is a class and Collection is an interface. Although there is only one "s" difference, their meanings are completely different. (Usage and difference of Comparator and Comparable and Collections and Collection)
Suppose there is such a linked list:
- Jsonlist list = new jsonlist ();
- List. add (4 );
- List. add (34 );
- List. add (22 );
- List. add (2 );
We only need to use:
- Collections. sort (list );
You can sort the elements in ll in the ascending order, and the result is:
- [2, 4, 22, 34]
If the element in the SORT list is String, the basic data type is also sorted from small to large.
If you want to implement reverse sorting, that is, sorting from large to small:
- Collections. sort (list, Collectons. reverseOrder ());
1 public class Sort2 { 2 public static void main(String[] args) { 3 LinkedList<Integer> list=new LinkedList<Integer>(); 4 list.add(4); 5 list.add(34); 6 list.add(22); 7 list.add(2); 8 Collections.sort(list, Collections.reverseOrder()); 9 System.out.println(list.toString());10 }11 }
Result: [34, 22, 4, 2]
If the elements in the sorted list are custom objects, You can implement the Comparable interface like the Name object above, so that Collection. sort () can be sorted for you.
If you want to sort an object according to your own ideas, you can use
- Sort (List <T> list, Comparator <? Super T> c)
Before providing an example, we need to describe the use of Comparator. The format of the Comparable interface is as follows:
- Public interface Comparator <T> {
- Int compare (T o1, T o2 );
- }
In fact, the write method of int compare (T o1, T o2) in Comparator is similar to that of compareTo () in Comparable. In the above Name class, our comparison started with LastName. This is a habit of Westerners. In China, we want to compare it from fristName and do not want to modify the original code. At this time, comparator can be used:
- Final Comparator <Name> FIRST_NAME_ORDER = new Comparator <Name> (){
- Public int compare (Name n1, Name n2 ){
- Int firstCmp = n1.firstName. compareTo (n2.firstName );
- Return (firstCmp! = 0? FirstCmp: n1.lastName. compareTo
- (N2.firstName ));
- }
- };
So that we can write a custom Comparator FIRST_NAME_ORDER.
Convert the name array in the previous example to List:
- List <Name> list = Arrays. asList (nameArray );
- Collections. sort (list, FIRST_NAME_ORDER );
In this way, we can use our own comparator to set the sorting.