如果我有以下课程:
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;
}
}