Comparable and Comparator -Part 3

Using Arrays.sort() and Collections.sort() with Comparable

In EmployeeComparision class in part 2 you have compared two employees using 'if 'clause as:

if(emp1.compareTo(emp2) < 0)

This is good for comparing only two employees but in real situations there may be many employees and you may have an array or a list containing them. Then you can use sort() method of Arrays class as:
import java.util.Arrays;

public class EmployeeComparision{
    public static void main(String args[]){
        Employee emp1 = new Employee();      
        emp1.setName("Mr. A");
        Employee emp2 = new Employee();      
        emp2.setName("Mr. B");
        emp2.setCity("Los Angeles");
        Employee emp3 = new Employee();      
        emp3.setName("Mr. C");
        Employee emp4 = new Employee();      
        emp4.setName("Mr. D");
        emp4.setCity("Los Angeles");
        Employee emp5 = new Employee();      
        emp5.setName("Mr. E");
        /* An array containing Employees */
        Employee [] empArray = new Employee[5];
        System.out.println("Employees in acsending order(according to their ids):");

        for(int i=0;i<=4;i++){
        System.out.println(empArray[i].getName()+", ");


Similarly you can use Collections.sort() in above code. Collections.sort() accepts List as argument instead of an array:

/* A List containing Employees */
  List<Employee> empList = new ArrayList<Employee>();
 System.out.println("Employees in acsending order(according to their ids):");

 for(int i=0;i<empList.size();i++){
  System.out.println(empList.get(i).getName()+", ");

So up to now in part 1, part 2, part 3 and in part 4 you have been writing code to sort your Employee instances based on their ids. But suppose now you have a requirement of sorting employess in ascending order of their names also. What would you do? Would you change logic in compareTo() method for sorting employess according to their names? -- Nah!

And suppose sometimes later you again have a requirement of sorting your employees according to their salary. Would you again change compareTo() for this?  Again Nah!

What you need for this is Comparator interface.

Click on Next >> to read about Comparator.

I would like to know your comments and if you liked the article then please share it on social networking buttons.

1 comment:

  1. Collections.sort(empList) will throw ClassCastException.