Comparable vs Comparator

javalearning Published on 15 February 2020

In Java programming language, an interface is used to specify a behaviour that classes must implement. Java world offers us two such interfaces Comparable and Comparator! Comparable in Java is used to sort the objects with natural ordering while Comparator is used to sort the attributes of different objects.


What is Comparable in Java?

As the name itself suggests, Comparable is an interface that defines a way to compare an object with other objects of the same type. It helps to sort the objects that have self-tendency to sort themselves, i.e., the objects must know how to order themselves. Eg: Roll number, age, salary. This interface is found in java.lang package and it contains only one method, i.e., compareTo(). Comparable is not capable of sorting the objects on its own, but the interface defines a method int compareTo() which is responsible for sorting.


What is the compareTo method and how it is used?


This method is used to compare the given object with the current object. The compareTo() method returns an int value. The value can be either positive, negative, or zero. So now we are well acquainted with the theoretical knowledge of Comparable interface in Java and compareTo method.



What is Comparator in Java?


A Comparator interface is used to order the objects of a specific class. This interface is found in java.util package. It contains two methods;


  1. compare(Object obj1,Object obj2)
  2. equals(Object element)


The first method, compare(Object obj1,Object obj2) compares its two input arguments and showcase the output. It returns a negative integer, zero, or a positive integer to state whether the first argument is less than, equal to, or greater than the second.


The second method, equals(Object element), requires an Object as a parameter and shows if the input object is equal to the comparator. The method will return true, only if the mentioned object is also a Comparator. The order remains the same as that of the Comparator.


I hope the above-mentioned differences brought some clarity regarding the two concepts.