what is the difference between comparable and comparator

In this tutorial we will learn what is the difference between comparable and comparator interfaces , and when we need to use comparable and when we need to use comparator.

Basically “what is the difference between comparable and comparator ? ” is one of the Java interview question,  and in Java we have two interfaces which are using to sort collection objects, one is comparable interface from java.lang package and another one is comparator from java.util package. Based on the requirement we need to use either of these.


Let us have a example code how to implement sorting by using comparable and comparator interfaces.

Sorting by using comparable interface.

When ever the class implements Comparable interface  then collection of that object (Student class here) can be sorted automatically by using Collection.sort() , for to implement sorting mechanism we need to override compareTo() method in our class which we need to sort.

Here in test program we are calling Collection.sort() method to sort the collection of Student objects based on the id.



Sorting by using comparator interface.

When ever we want to sort our userdefined objects based on the specific property then we will use “Comparator” interface , to achieve the sorting mechanism first we need write separate class which is subtype of Comparator interface and use that class to sort our objects.


Here we implemented  “EmployeeSortByComparator” class which is used sort our employee objects based on the empId , by using comparator we can write any specific sorting logic based on the properties of our defined object.


In below test program we are using Collections.sort(alist,new EmployeeSortByComparator()) method to sort out our Employee objects by passing the  EmployeeSortByComparator to Collections.sort() method.





A comparable object is used to  comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances


A comparator object is used to  comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.


Download  Source Code











Posted in InterviewQuestions and tagged , , .

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">