/*
* TreeSet的定制排序:
* //1.创建一个实现了Comparator接口的类对象
* //2.将此对象作为形参传递给TreeSet的构造器中
* //3.向TreeSet中添加Comparator接口中的compare方法中涉及的类的对象
*
* compare()与hashCode()以及equals()三张保持一致!
*
*/
public void testTreeSet() {
//1.创建一个实现了Comparator接口的类对象
Comparator com =new Comparator() {
//向TreeSet中添加Customer类的对象,在此Comparator()方法中,指明是
//按照Customer的哪个属性进行排序的。
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if(o1 instanceof Customer && o2 instanceof Customer){
Customer c1 = (Customer)o1;
Customer c2 = (Customer)o2;
int i = c1.getId().compareTo(c2.getId());
if(i == 0) {
return c1.getName().compareTo(c2.getName());
}else {
return i;
}
}
return 0;
}
};
//2.将此对象作为形参传递给TreeSet的构造器中
TreeSet set = new TreeSet(com);
//3.向TreeSet中添加Comparator接口中的compare方法中涉及的类的对象
set.add(new Customer("CC",23));
set.add(new Customer("GG",22));
set.add(new Customer("DD",22));
set.add(new Customer("DD",22));
}
}