首页 > 代码库 > Java TreeSet的定制排序

Java TreeSet的定制排序

注:只贴出实现类

package Test3;

import java.util.Comparator;
import java.util.TreeSet;

public class Test {

public static void main(String[] args) {
Comparator com=new Comparator() {①创建一个Comparator接口的匿名内部类

@Override
public int compare(Object o1, Object o2) {②重写compare方法,定制排序的方法
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("胡",23,new MyDate(1992,10,27));
Employee e2=new Employee("赵",19,new MyDate(1996,10,27));
Employee e3=new Employee("钱",21,new MyDate(1994,10,27));
Employee e4=new Employee("孙",22,new MyDate(1993,10,27));
Employee e5=new Employee("李",20,new MyDate(1995,10,27));

TreeSet<Employee> set=new TreeSet<Employee>(com);③把实现Comparator接口的对象传递到TreeSet构造器
set.add(e1);
set.add(e2);
set.add(e3);
set.add(e4);
set.add(e5);

for(Employee e:set){
System.out.println(e);
}
}
}

Java TreeSet的定制排序