According to the agreement, when using Java programming, you should use existing class libraries as much as possible. Of course, you can also write a sorting method or framework yourself, but how many people can write better than those in the JDK? Another benefit of using existing classes is that the code is easy to read and maintain. This article mainly talks about how to use existing class libraries to sort arrays and various Collection containers. (Some examples in the article come from "Java Developers Almanac 1.4》)
First of all, you need to know two classes: java.util.Arrays and java.util.Collections (note the difference with Collection) Collection is the top-level interface of the collection framework, and Collections contains many static methods. We use Arrays to sort arrays and Collections to sort combined frame containers, such as ArraysList, LinkedList, etc.
Import java.util.* and other shell codes, such as classes and static main methods, must be added to the examples. I will write all the codes in the first example, and will omit them without exception in the following.
Sort array
For example, there is an array of integers:
Copy the code code as follows:
int[] intArray = new int[] {4, 1, 3, -23};
How do we sort it? Are you thinking about the quick sort algorithm at this time? Take a look at how this is done:
Copy the code code as follows:
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 the intArray in ascending order. Now the array has become {-23,1,3,4}.
If it is a character array:
Copy the code code as follows:
String[] strArray = new String[] {"z", "a", "C"};
We use:
Copy the code code as follows:
Arrays.sort(strArray);
The result after sorting is {C, a, z}, and sort() will sort in ascending order according to the natural order of the elements. If you want to be case-insensitive, you can write:
Copy the code code as follows:
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
Of course, we can also specify a certain section of the array to sort. For example, if we want to sort parts 0-2 of the array (assuming the array length is greater than 3), and the other parts remain unchanged, we can use:
Copy the code code as follows:
Arrays.sort(strArray,0,2);
In this way, we only sort the first three elements without affecting the following parts.
Of course some people will think, how do I sort in descending order? Among the many sort methods, one copy of the code is as follows:
sort(T[] a, Comparator<? super T> c)
We can use Comparator to obtain a comparator in reverse order. Comparator will be explained later. Take the previous intArray[] as an example:
Copy the code code as follows:
Arrays.sort(intArray,Comparator.reverseOrder());
In this way, the result we get is {4,3,1,-23}. If we don’t want to modify the original code we can also use:
Copy the code code as follows:
Collections.reverse(Arrays.asList(intArray));
Get the reverse order of the array. The result is also 4,3,1,-23}.
Now the situation has changed. Our array is no longer an array of primitive data type (primitive 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:
Copy the code code as follows:
class Name implements Comparable<Name>{
public String firstName,lastName;
public Name(String firstName,String lastName){
this.firstName=firstName;
this.lastName=lastName;
}
public int compareTo(Name o) { //Implement the interface
int lastCmp=lastName.compareTo(o.lastName);
return (lastCmp!=0?lastCmp:firstName.compareTo(o.firstName));
}
public String toString(){ //Convenient for output testing
return firstName+" "+lastName;
}
}
In this way, when we sort this object array, we will first compare lastName, then compare firstName, and then get the order of the two objects, just like what is implemented in compareTo(Name o). You might as well try it with the program:
Copy the code code as follows:
import java.util.*;
public class NameSort {
public static void main(String[] args) {
Name nameArray[] = {
new Name("John", "Lennon"),
new Name("Karl", "Marx"),
new Name("Groucho", "Marx"),
new Name("Oscar", "Grouch")
};
Arrays.sort(nameArray);
for(int i=0;i<nameArray.length;i++){
System.out.println(nameArray[i].toString());
}
}
}
The result is as we expected:
Copy the code code as follows:
Oscar Grouch
John Lennon
Groucho Marx
Karl Marx
Sort collection frames
If you have understood Arrays.sort() to sort arrays, the use of the collection framework is similar. Just 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.
Suppose there is such a linked list:
Copy the code code as follows:
LinkedList list=new LinkedList();
list.add(4);
list.add(34);
list.add(22);
list.add(2);
We just need to use:
Copy the code code as follows:
Collections.sort(list);
You can sort the elements in ll from small to large, and the result becomes:
Copy the code code as follows:
[2, 4, 22, 34]
If the elements in the LinkedList are Strings, they will also be sorted from small to large like the basic data types.
If you want to implement reverse sorting, that is, from reaching to small sorting:
Copy the code code as follows:
Collections.sort(list,Collectons.reverseOrder());
If the elements in the LinkedList are custom objects, you can implement the Comparable interface like the Name object above, and then let Collection.sort() sort them for you.
If you want to sort an object according to your own ideas, you can use the copied code as follows:
sort(List<T> list, Comparator<? super T> c)
This method performs sorting. Before giving an example, we must first explain the use of Comparator and the format of the Comparable interface:
Copy the code code as follows:
public interface Comparator<T> {
int compare(T o1, T o2);
}
In fact, the writing method of int compare(T o1,T o2) in Comparator is similar to the writing method of compareTo() method in Comparable. In the above Name class, our comparison starts from LastName. This is the habit of Westerners. In China, we want to start the comparison from fristName without modifying the original code. At this time, Comparator can come in handy:
Copy the code code as follows:
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));
}
};
In this way, our customized Comparator FIRST_NAME_ORDER is written.
Convert the array of names in the previous example into a List:
Copy the code code as follows:
List<Name> list=Arrays.asList(nameArray);
Collections.sort(list,FIRST_NAME_ORDER);
In this way, we successfully set the sorting using our own defined comparator.