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 implementation.

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

Employee is class that will implement compare To 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.

abu murad

Abu Murad , is fascinated by the constantly changing, complex, layered world of SEO, & content marketing’s ability to reach potential buyers on their terms, in their timing, and in the ways that are most relevant to them.

Leave a Comment