Data Sorting in arraylist-Java object sorting

Source: Internet
Author: User

I often encounter array sorting problems. For example, I have a person class whose instance objects are stored in the arraylist array. Now I want to sort the person objects in the arraylist array by age.
In fact, this situation is often encountered.
The source code is as follows:

1: person. Java file :-------------------------------
Public class person {
String name;
Int age;
 
Public Person (string name, int age ){
This. Name = Name;
This. Age = age;

}

Public int getage (){
Return age;
}

Public void setage (INT age ){
This. Age = age;
}

Public String getname (){
Return name;
}

Public void setname (string name ){
This. Name = Name;
}

}

2: mycomparator. Java -------------------------------
// Implement the comparator interface, that is, to define sorting rules. You can define almost any rule
Package com. infoearth;
Import java. util .*;
Public class mycomparator implements comparator {

Public int compare (Object O1, object O2 ){
Person p1 = (person) O1;
Person P2 = (person) O2;
If (p1.age <p2.age)
Return 1;
Else
Return 0;
}

}

3: listsort. Java ------------------------------------

Package com. infoearth;

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

Public class listsort {
Public static void main (string [] ARGs ){
Arraylist list = new arraylist ();
List. Add (new person ("LCL", 28 ));
List. Add (new person ("FX", 23 ));
List. Add (new person ("wqx", 29 ));
Comparator comp = new mycomparator ();
Collections. Sort (list, comp );
For (INT I = 0; I <list. Size (); I ++ ){
Person P = (person) list. Get (I );
System. Out. println (P. getname ());
}

}

}

I am here to archive it and hope it will help you.

Related Article

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.