How to sort custom objects in Java

Source: Internet
Author: User

Import java. util. comparator;
Import java. util. arraylist;

 

Public class demo {
Public static void main (string [] ARGs ){


User U1 = new user ("AAA", 12 );
User U2 = new user ("DDD", 10 );
User U3 = new user ("CCC", 20 );
User U4 = new user ("BBB", 10 );

Arraylist = new arraylist ();
Arraylist. Add (U1 );
Arraylist. Add (U2 );
Arraylist. Add (U3 );
Arraylist. Add (U4 );

Object [] users = arraylist. toarray ();
System. Out. println ("Before sorting .... ");
For (INT I = 0; I <users. length; I ++ ){
System. Out. println (users [I]);
}
System. out. println ("*******************************");
System. Out. println ("sorted ..... ");
// Submit the sorting rule to the sort method. This method is sorted according to your custom rules.

Java. util. arrays. Sort (users, new mycomparator ());


For (INT I = 0; I <users. length; I ++ ){
System. Out. println (users [I]);
}



}
}

Class user {
String name;
Int age;
 
Public user (string name, int age ){
This. Name = Name;
This. Age = age;
}
 
Public String tostring (){
Return name + ":" + age;
}
 
}

Class mycomparator implements comparator {
Public int compare (Object obj1, object obj2 ){
User U1 = (User) obj1;
User U2 = (User) obj2;
If (u1.age> u2.age ){
Return 1;
} Else if (u1.age <u2.age ){
Return-1;
} Else {
// Use the sorting method of the string itself.
// Sort by name if the age is the same
Return u1.name. compareto (u2.name );
}


}
}

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.