![]() |
#2
林月儿2018-10-19 23:19
|

/*
* 向TreeSet集合中加入5个员工的对象
* 根据员工的年龄(升序)进行排序
* 若年龄相同,再根据工龄(降序)来排序
* 若工龄相同,再根据薪水(降序)排序
* 若薪水相同,再根据姓名首字母升序排列
*/
public class StaffCompare implements Comparator<Staff>{
public int compare(Staff o1, Staff o2) {
int n1 = o1.getAge() - o2.getAge();
int n2 = o1.getWorkAge() - o2.getWorkAge();
int n3 = (o1.getSalary(), o2.getSalary());
boolean n4 = o1.getName().equals(o2.getName());
return (0==n1) ? ((0==n2)? (n3==0 ? -1 : (n3<0 ? 1 : -1)) : (n2<0? 1: -1)):(n1>0? 1:-1);
}
}
* 向TreeSet集合中加入5个员工的对象
* 根据员工的年龄(升序)进行排序
* 若年龄相同,再根据工龄(降序)来排序
* 若工龄相同,再根据薪水(降序)排序
* 若薪水相同,再根据姓名首字母升序排列
*/
public class StaffCompare implements Comparator<Staff>{
public int compare(Staff o1, Staff o2) {
int n1 = o1.getAge() - o2.getAge();
int n2 = o1.getWorkAge() - o2.getWorkAge();
int n3 = (o1.getSalary(), o2.getSalary());
boolean n4 = o1.getName().equals(o2.getName());
return (0==n1) ? ((0==n2)? (n3==0 ? -1 : (n3<0 ? 1 : -1)) : (n2<0? 1: -1)):(n1>0? 1:-1);
}
}
员工类中:
私有属性:姓名name,年龄age,工龄workage,工资salary;
并且重写了hashCode和equals。
main测试中:
用Iterator遍历出结果。
大家看看比较器Comparator有没有别的方式?