Java _ Implementation of two Comparator

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.