Wednesday, July 27, 2011

Collection of user defined comparable objects (Part 2)

Yesterday we discussed how to make user defined objects comparable to themselves. Let’s take that to one step further today. In yesterdays post, our requirement was to sort the collection of employees that belong to a division, by employee id, so that the end result will be a collection of employees in seniority order.

Now there comes the payroll division and it says, for each division, you need to print the list of employees based on the salary drawn. You may say “It is very simple; I had done all the ground work yesterday; so just need to change the comparison logic as below”.

public class Employee implements Comparable<Employee> {
private String name;
private int employeeNo;
private float salary;

public int compareTo(Employee e) {
if (salary == e.salary) {
return 0;
} else if (salary > e.salary) {
return 1;
} else {
return -1;
}
}
}

Now the human resources division shouts “What have you done? Now employees are not in seniority order, everything is messed up”. What are you going to do to make you employee objects comparable to themselves based on employeeNo and salary?

What is clear here is that we need to move the comparison logic outside the Employee class but at the same time we should be able to sort the collection of employees based on a given field. So let’s remove the comparison logic.

public class Employee{
private String name;
private int employeeNo;
private float salary;

public int getEmployeeNo() {
return employeeNo;
}

public float getSalary() {
return salary;
}
}

Where should we place the comparison logic now? Let’s make use of java.util.Comparator.

class SalaryComparator implements Comparator<Employee> {

public int compare(Employee e1, Employee e2) {
if (e1.getSalary() == e2.getSalary()) {
return 0;
} else if (e1.getSalary() > e2.getSalary()) {
return 1;
} else {
return -1;
}
}
}

class SeniorityComparator implements Comparator<Employee> {

public int compare(Employee e1, Employee e2) {
return e1.getEmployeeNo() - e2.getEmployeeNo();
}
}

Comparison logic is ready. How can we use this in sorting?
List<Employee> list1 = ...
Collections.sort(list1, new SalaryComparator());
List<Employee> list2 = ...
Collections.sort(list2, new SeniorityComparator());

That’s all. You have solved the issues of HR division and Payroll division.