Java Sorting using Comparable

In Java you can do sorting by implementing 2 interfaces
1) Comparable
2) Comparator

Here we will see sorting example using Comparable Interface. As an example we will be sorting objects of Employee class.

When using comaprable interface make sure the object class
which you are sorting implements comaprable interface and override compareTo method correctly.

As I was more used to Java 1.4, I didnt followed any Java Generics implemetation.

SortTest is main class that will actually creaate an array list and fill it with some random Employee objects.

Employee is class that will implement compareTo method. I have added simple if-else control structure that will decide what to return on the basis of employee id.
less : -1           equal : 0           greater : 1

Here is the code for classes:

Output:
sort_comparable
Limitations:

  1. Objects should be mutally comparable. i.e you can not compare objects of different classes.
  2. Using comparable binds sorting to one perticular strategy.
    e.g. In above example we have sorted using employee id to compare. now if we need to sort on employee name it will be difficult.

Next, I will be putting similar example using Comparator Interface.

One Comment
  1. Praveen
    October 19, 2011 | Reply

Add a Comment

Your email address will not be published. Required fields are marked *