1

I have an employee class & a client class. I am able to sort using compareTo() via Employee's id & age as they are of integer type. But how do I sort by employee's name or salary? compareTo is not accepting any data type other than int, throws a compile time exception.

public class Employee implements Comparable<Employee> {

    private int id;
    private String name;
    private int age;
    private long salary;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public long getSalary() {
        return salary;
    }

    public Employee(int id, String name, int age, int salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    @Override
    public int compareTo(Employee emp) {
        //let's sort the employee based on id in ascending order
        //returns a negative integer, zero, or a positive integer as this employee id
        //is less than, equal to, or greater than the specified object.
        return (this.age - emp.age);
    }

    @Override
    //this is required to print the user friendly information about the Employee
    public String toString() {
        return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
                this.salary + "]";
    }

}

Client class

import java.util.Arrays;

public class Test {

    public static void main(String a[]){

        //sorting custom object array
        Employee[] empArr = new Employee[4];
        empArr[0] = new Employee(10, "Mikey", 25, 10000);
        empArr[1] = new Employee(20, "Arun", 29, 20000);
        empArr[2] = new Employee(5, "Lisa", 35, 5000);
        empArr[3] = new Employee(1, "Pankaj", 32, 50000);

        //sorting employees array using Comparable interface implementation
        Arrays.sort(empArr);
        System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr));

    }
}

I just googled seems like I can also achieve it by implementing comparator

public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return (int) (e1.getSalary() - e2.getSalary());
        }
    };

Which one is advisable using the comparator or

@Override
public int compareTo(Employee emp) {
// compare salaries, using the builtin Long.compare:
    return Long.compare (salary, emp.salary);
}
4
  • compareTo wants you, according to the documentation of Comparable, to return an int describing the ternary comparison result (less, equal, or greater than), don't confuse that. Commented May 7, 2014 at 6:15
  • I know that I want to know how to compare by the name? Commented May 7, 2014 at 6:17
  • As your name is a String and String implements Comparable as well, just reuse it: return this.name.compareTo(emp.name); Commented May 7, 2014 at 6:19
  • Use index to get fields by name and use it in the comparator model. Commented May 7, 2014 at 6:32

3 Answers 3

4

If you want to sort based on name, you can try

@Override
    public int compareTo(Employee emp) {
        return this.name.compareTO(emp.name);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

this will not work if you are using a primitive type like int. Age is declared as an int.
1

Basically, you want to sort your class based on several properties. The trick here is to decide the order in which they should be evaluated, and treat one as a Comparable on its own right. If the comparison isn't 0 - you found which instance should come before the other, and you can just return the value. If not, you need to evaluate a different property.

E.g., assuming the properties you want to use are id, age, name and salary:

@Override
public int compareTo(Employee emp) {
    // compare IDs:
    int cmp = Integer.compare(id, emp.id);
    if (cmp != 0) {
        return cmp;
    }

    // compare ages:
    cmp = Integer.compare(age, emp.age);
    if (cmp != 0) {
        return cmp;
    }

    // compare names. Luckily, Strings are comparable:
    cmp = name.compareTo(emp.name);
    if (cmp != 0) {
        return cmp;
    }

    // compare salaries, using the builtin Long.compare:
    return Long.compare (salary, emp.salary);
}

Comments

1

I would implement compareTo this way:

public int compareTo(Employee emp) {
    return Integer.compare(this.age, emp.age);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.