1. Implement the comparable interface for objects in the list:
Public class user implements comparable <user> {private string name; private integer order; Public String getname () {return name;} public void setname (string name) {This. name = Name;} public integer getorder () {return order;} public void setorder (integer order) {This. order = order;} public int compareto (User arg0) {return this. getorder (). compareto (arg0.getorder ());}}
Below is the test class:
Import Java. util. arraylist; import Java. util. collections; import Java. util. list; public class test {public static void main (string [] ARGs) {user user1 = new user (); user1.setname ("A"); user1.setorder (1 ); user user2 = new user (); user2.setname ("B"); user2.setorder (2); list <user> List = new arraylist <user> (); // Add user2 and then add user1 list. add (user2); list. add (user1); collections. sort (list); For (User U: List) {system. out. println (U. getname ());}}}
Output:
A
B
2. Use static internal classes to implement the comparator interface. The comparator interface is located under the java. util package.
Import Java. util. *; public class main {public static void main (string ARGs []) {arraylist Al = new arraylist (); Al. add (new student (2, "AA"); Al. add (new student (1, "BB"); Al. add (new student (3, "DD"); Al. add (new student (3, "cc"); collections. sort (Al, new studentcomparator (); iterator it = Al. iterator (); While (it. hasnext () {system. out. println (it. next () ;}} class student {int ID; string name; student (int id, string name ) {This. id = ID; this. name = Name;} Public String tostring () {return "id =" + this. ID + ", name =" + this. name ;}} class studentcomparator implements comparator {public int compare (Object O1, object O2) {student S1 = (student) O1; Student S2 = (student) O2; int result = (s1.id> s2.id )? 1 :( (s1.id = s2.id )? 0:-1); If (0 = Result) {result = s1.name. compareto (s2.name) ;}return result ;}}
3. Added: The problem I encountered was to directly list <string> List = new arraylist ();
In this case, if we call the collections. Sort (list); method, it sorts the ASCII values of the strings in the list from left to right.ComparatorInterface.
Public class connectionssort {public static void main (string [] ARGs) {// todo auto-generated method stublist <string> List = new arraylist (); Int J = 0; jdbmanager DB = new jdbmanager (); resultset RS; string q = "select * From securityevent"; try {rs = db.exe cutequery (Q); While (RS. next () {list. add (RS. getstring ("Grade");} collections. sort (list); While (j <list. size () {system. out. println (list. get (j ). tostring (); j ++;} catch (exception e) {// todo: handle exception }}}
The experiment results are as follows:
A
A
B
B
B
C
C
C
D