Note: Only the implementation class is posted
Package Test3;
Import Java.util.Comparator;
Import Java.util.TreeSet;
public class Test {
public static void Main (string[] args) {
Comparator com=new Comparator () {① Create an anonymous inner class for the Comparator interface
@Override
public int Compare (object O1, Object O2) {② Rewrite Compare method, custom Sort method
if (O1 instanceof employee && O2 instanceof Employee) {
Employee e1= (employee) O1;
Employee e2= (employee) O2;
MyDate Birth1=e1.getbirthday ();
MyDate Birth2=e2.getbirthday ();
if (Birth1.getyear ()!=birth2.getyear ()) {
Return Birth1.getyear ()-birth2.getyear ();
}else{
if (Birth1.getmonth ()!=birth2.getmonth ()) {
Return Birth1.getmonth ()-birth2.getmonth ();
}else{
if (Birth1.getday ()!=birth2.getday ()) {
Return Birth1.getday ()-birth2.getday ();
}
}
}
}
return 0;
}
};
Employee E1=new employee ("Hu", 23,new mydate (1992,10,27));
Employee E2=new employee ("Zhao", 19,new mydate (1996,10,27));
Employee E3=new Employee ("Money", 21,new mydate (1994,10,27));
Employee E4=new Employee ("Sun", 22,new mydate (1993,10,27));
Employee E5=new Employee ("Lee", 20,new MyDate (1995,10,27));
treeset<employee> set=new treeset<employee> (COM);③ passing objects that implement the comparator interface to the TreeSet constructor
Set.add (E1);
Set.add (E2);
Set.add (E3);
Set.add (E4);
Set.add (E5);
for (Employee E:set) {
System.out.println (e);
}
}
}
Customizing sorting for Java TreeSet