注册 登录
编程论坛 JAVA论坛

TreeSet重写Comparator排序

悟空丨 发布于 2018-10-19 23:15, 2302 次点击
程序代码:
/*

 * 向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有没有别的方式?
3 回复
#2
林月儿2018-10-19 23:19
Comparable
#3
悟空丨2018-10-19 23:26
回复 2楼 林月儿
好的,我去试试~~~
#4
TysonKoothra2018-10-21 21:21
这个三元操作符用的好长。
1