如何正确使用Java比较器?
发布时间:2020-05-24 17:32:30 所属栏目:Java 来源:互联网
导读:如果我有以下课程: public class Employee { private int empId; private String name; private int age; public Employee(int empId, String name, int age) { // set values on attributes }
|
如果我有以下课程: public class Employee {
private int empId;
private String name;
private int age;
public Employee(int empId,String name,int age) {
// set values on attributes
}
// getters & setters
}
如何使用按名称比较的比较器,然后是年龄,然后是id? 解决方法您需要实现它,以便按首选元素进行排序.也就是说,您需要按名称进行比较,然后如果该比较相等,则按年龄等进行比较.下面列出了一个示例:public class EmployeeComparator implements Comparator<Employee> {
@Override
public int compare(Employee e1,Employee e2) {
int nameDiff = e1.getName().compareTo(e2.getName());
if(nameDiff != 0) {
return nameDiff;
}
int ageDiff = e1.getAge() - e2.getAge();
if(ageDiff != 0) {
return ageDiff;
}
int idDiff = e1.getEmpId() - e2.getEmpId();
return idDiff;
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
