Entity object Class--slightly
Sort class----Implement the comparator interface, overriding the Compare method
Package com.tang.list;
Import Java.util.Comparator;
public class Mycompera implements comparator<student> {
@Override
public int Compare (Student O1, Student O2) {
if (O1.getsid () > O2.getsid ()) {
return-1;
}
return 1;
}
}
Test Class--------------------------
Package com.tang.list;
Import java.util.ArrayList;
Import java.util.Collections;
Import java.util.List;
public class Listsorttang {
Sort by the properties of the objects in the list
public static void Main (string[] args) {
Student st1 = new Student (1, "a", "male", 12);
Student st2 = new Student (2, "B", "female", 11);
Student st3 = new Student (3, "C", "male", 20);
Student st4 = new Student (4, "D", "female", 15);
Student st5 = new Student (5, "E", "male", 32);
Student St6 = new Student (6, "F", "female", 21);
Student st7 = new Student (7, "G", "male", 12);
Student st8 = new Student (8, "H", "female", 10);
Student st9 = new Student (9, "I", "male", 9);
Student st10 = new Student (Ten, "J", "female", 19);
list<student> stus = new arraylist<student> ();
Stus.add (ST1);
Stus.add (ST2);
Stus.add (ST3);
Stus.add (ST4);
Stus.add (ST8);
Stus.add (ST5);
Stus.add (ST6);
Stus.add (ST7);
Stus.add (ST9);
Stus.add (ST10);
for (Student s:stus) {
System.out.println (S.tostring ());
}
System.out.println ("after sorting .........");
Collections.sort (Stus, New Mycompera ());//Sort
for (Student s:stus) {
System.out.println (S.tostring ());
}
}
}
Output-------------------
Student [Sid=1, Name=a, sex= man, age=12]
Student [sid=2, Name=b, sex= female, age=11]
Student [Sid=3, Name=c, sex= man, age=20]
Student [Sid=4, Name=d, sex= female, age=15]
Student [Sid=8, Name=h, sex= female, age=10]
Student [Sid=5, Name=e, sex= man, age=32]
Student [Sid=6, Name=f, sex= female, age=21]
Student [Sid=7, Name=g, sex= man, age=12]
Student [Sid=9, Name=i, sex= man, Age=9]
Student [sid=10, Name=j, sex= female, age=19]
After the sort ....... .....
Student [sid=10, Name=j, sex= female, age=19]
Student [Sid=9, Name=i, sex= man, Age=9]
Student [Sid=8, Name=h, sex= female, age=10]
Student [Sid=7, Name=g, sex= man, age=12]
Student [Sid=6, Name=f, sex= female, age=21]
Student [Sid=5, Name=e, sex= man, age=32]
Student [Sid=4, Name=d, sex= female, age=15]
Student [Sid=3, Name=c, sex= man, age=20]
Student [sid=2, Name=b, sex= female, age=11]
Student [Sid=1, Name=a, sex= man, age=12]
Java sorts objects in list by attributes