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.