Example of Java Classic Programming 300 example 063 custom sort using comparable interface
case See http://blog.csdn.net/the_star_is_at/article/details/70245219
Example description
By default, arrays saved in the list collection are not sorted, but you can customize collations by using the comparable interface and automatically sort. This example describes how to use the comparable interface to customize collations and sort them automatically.
Implementation process
Creates a new Java class with the name employee. In this class, you first define 3 properties, is the ID (the number of the employee), name (the name of the employee), and age (for the employee), and then initialize the 3 properties in the constructor, and finally implement the CompareTo () method defined in the interface, sorting the objects in ascending order by number.
Employee.java
[Java] View Plain copy public class employee implements comparable<employee> { private int id; private String name; private int age; public employee (int id, string name, int age) { // Initialize each domain this.id = id; with the constructor method this.name = name; this.age = age; } @Override public int compareto (Employee o) { //comparison between objects by using numbering if (id > o.id) { return 1; } else if (id < o.id) { return -1; } return 0; } @Override Public string tostring () { //-Rewrite ToString () method stringbuilder sb = new stringbuilder (); &nbSp; sb.append ("Employee's number:" + id + ","); sb.append ("Employee's name:" + name + "T,"); sb.append ("Age of the Staff:" + age); return sb.tostring (); } }
When overriding a method in an interface, restrict the access permission to public, because the method in the interface is subscript character by default.
Then create a new class called Test, which is used for testing. In this class, you first define a list collection to hold 3 employee objects and then perform automatic sorting by traversing the elements in the output collection and then by Collections.sort (), and then by traversing the elements in the sorted collection.
Test.java
[Java] view plain copy import java.util.ArrayList; Import java.util.Collections; Import java.util.List; public class Test {public static void main (string[] args) {list<employee> List = new arraylist< Employee> (); List.add (