Using the collections. sort method to complete a small sorting function, you also have a simple understanding of the collections. sort method.
The sorting of Java Collection classes mainly uses the collections. sort method. Collections and collection are different. The former is a class, and the latter is an interface. Tip: when implementing the interface method, you only need to compare two numbers. If the value is large, 1 is returned. If the value is equal, 0 is returned, and less than-1 is returned. Simply put, write "Num> S. Num?" In the method? 1 :( num = S. Num? 0:-1); num indicates the number to be compared, and S. Num indicates the number to be compared,
1. collection. Sort (list arg0 );
This is the simplest sorting method. You only need to implement its comparable interface and the Public int compareto (Object arg0) method.
If you want to sort people in the list array, you only need to collect. Sort (people.
2. collection. srot (list arg0, comparator arg1 );
The comparator is added to facilitate management with greater flexibility. The comparator can be used as an internal static class for ease of management. The comparator must implement the comparator interface.
If you want to sort objects by a certain attribute in the list, you need to add a comparator. For example, if people is a people object set and the people object has the age attribute, you need to sort all people objects by age. The Code is as follows:
Add the internal static class peoplecomparator to the people class:
// Ignore the null age attribute
Public static class peoplecomparator implements comparator <people> {
Public int compare (People O1, people O2 ){
Return o1.getage (). compareto (o2.getage ());
}
}
The program has list <people> people. To sort the people set, add
Collections. Sort (people, new people. peoplecomparator.
I am comparing dishes. If there is any mistake, I hope the viewer will correct me. Thank you !!!! Haha ^_^