Comparable vs Comparator Interface in Java
Let’s learn about the comparable and comparator interface in java and when should we use them
Comparable and Comparator are used when we want to sort a collection in Java. But in what situation should we use Comparable or Comparator Interface? What are the differences between Comparable and Comparator Interface? In this article, I will explain both the interfaces and the best situation to use them.
Comparable Interface is present in java.lang package and they only contain one method i.e.
public int compareTo(Object obj)
The method returns three values i.e. negative, position, and zero. Let’s take a simple example to understand in detail.
if obj1 comes before obj2 then it returns a negative number. if obj1 and obj2 are equal, then it returns 0. if obj1 comes after obj2 then it returns a positive number.
The Comparable interface is meant for default natural sorting. A Class must implement a comparable interface to compare its value. The problem with the Comparable interface is we only get one chance to implement the compareTo() method.
Let’s look at an example of a Student class that has properties id, rollNo, and name. We will sort it on the basis of id using the comparable interface.
The output will be:
But now we decided to add one more sorting method that sorts the object based on rollNo as well. To achieve this we have to remodify the logic we have kept on the compareTo() method. This won’t solve the problem if we want to add both sorting mechanisms that are sorting by id as well as sorting by roll no. To solve this problem, we have Comparator Interface.
Comparator Interface is used for customized sorting orders. The interface is present in java.util package and contains two methods i.e. compare() and equal(). The implementation of the equal method is optional because the object class already contains an equal method and by default, all its child class implements an equal method.
public int compare(Obj obj1, Obj obj2)
It returns a negative number if obj1 has come before obj2, and returns a positive number if obj1 has come after obj2. It returns zero if obj1 and obj2 are equal.
Let’s solve the problem described above by using Comparator Interface.
The output will be: