How to use Java comparator properly?

前端 未结 7 1625
孤街浪徒
孤街浪徒 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:18

    You can also implement the Comparable Interface in your class.

    for example, something like this:

    public class Employee implements Comparable{
        private int empId;
        private String name;
        private int age;
    
        public Employee(int empId, String name, int age) {
                // set values on attributes
    
        }
        // getters & setters
    
        public int compareTo(Employee o) {
            int ret = this.name.compareTo(o.name);
            if(ret == 0)
                ret = this.age - o.age;
            if(ret == 0)
                ret = this.empId - o.empId;
    
            return ret;
        }
    }
    

    so you don't have to implement a extra class to compare your Employees.

提交回复
热议问题