How to use Java comparator properly?

前端 未结 7 1647
孤街浪徒
孤街浪徒 2020-12-11 05:42

If I have the following class:

public class Employee {
    private int empId;
    private String name;
    private int age;

    public Employee(int empId, S         


        
7条回答
  •  温柔的废话
    2020-12-11 06:40

    You need to implement it so that it orders by preferred elements. That is, you need to compare by name, then if that comparison is equal, compare by age, etc. An example is listed below:

    public class EmployeeComparator implements Comparator {
    
      @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;
      }
    }
    

提交回复
热议问题