Package COM. KK. collection; import Java. util. arraylist; import Java. util. collections; import Java. util. comparator; import Java. util. list; public class comparetest {public static void main (string [] ARGs) {list <student> List = new arraylist <student> (10); list. add (new student (1, "JJ"); list. add (new student (0, "ww"); list. add (new student (0, "KK"); list. add (new student (2, "ll"); collections. sort (list); // internal comparison Tool: the comparable interface is implemented for the objects to be sorted. You can compare the system. out. println (list); List <teacher> T = new arraylist <teacher> (10); T. add (new teacher (1, 12); T. add (new teacher (0, 13); T. add (new teacher (0, 14); T. add (new teacher (2, 15); collections. sort (T, new studentcomparator (); // external comparator: implement the comparator interface system. out. println (t) ;}} class student implements comparable {int num; string name; Public student (INT num, string name ){ This. num = num; this. name = Name ;}@ override Public String tostring () {return "\ r \ tnum:" + num + "name:" + name + "\ r ";} public int compareto (Object O) {student TMP = (student) O; int result = TMP. num> num? 1 :( TMP. num = num? 0:-1); If (result = 0) {result = TMP. Name. indexof (0)> name. indexof (0 )? 1:-1;} return result;} class teacher {int num; double salary; public teacher (INT num, double salary) {This. num = num; this. salary = salary;} @ override Public String tostring () {return "\ r \ tnum:" + num + "Salary:" + salary + "\ r ";}} class studentcomparator implements comparator {public int compare (Object O1, object O2) {teacher T1 = (teacher) O1; teacher t2 = (teacher) O2; int result = t1.num> t2.num? 1 :( t1.num = t2.num? 0:-1); return result = Result = 0? (T1.salary <t2.salary? 1:-1): result ;}}
Source: http://www.cnblogs.com/BigIdiot/archive/2011/12/09/2282673.html