加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何正确使用Java比较器?

发布时间:2020-12-15 00:01:59 所属栏目: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 } // getters setters} 如何使用按名称比较的比较器,然后是年龄,然
如果我有以下课程:
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;
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读