Thursday, 25 October 2012

Comparable And Comparator

Comparator and Comparable

In java these are the most common question what is comparable? What is comparator? Difference between comparable and comparator? When to use comparable? When to use comparator?
So in this blog I will explain you what and when to use comparable and comparator. 

Before going to when to use comparable and comparator answer this let’s have a look on common and different behaviour of both.
  •  Both are interfaces. 
  •  Both used for sorting purposes. 


Defined in java.util package
Defined in java.lang package
Has to override this method
public int compareTo(Object o)  
Has to override this method
public int compare (Object o1, Object o2) 
Used to implement natural ordering of object
Used to implement external ordering of object
Any class implements Comparable interface then collection of that class object (either List or Array) can be sorted automatically using Collections.sort() or Array.sort() method which sorts the objects in natural order or in ascending order.
To sort using Comparator, external comparator is passed as a parameter in Collections.sort
Comparable Class
Comparator Class

When to use Comparable 
  • If there is a natural or default way of sorting Object already exist during development of Class than use Comparable.

When to use Comparator 

  • If an Object can be sorted on multiple ways and client is specifying on which parameter sorting should take place than use Comparator interface.
  • Some time you write code to sort object of a class for which you are not the original author, or you don't have access to code. In these cases you cannot implement Comparable and Comparator is only way to sort those objects
  • Beware with the fact that how those object will behave if stored in SorteSet or SortedMap like TreeSet and TreeMap. If an object doesn't implement Comparable than while putting them into SortedMap, always provided corresponding Comparator which can provide sorting logic. Thanks for reading.

profile for Ashish Aggarwal on Stack Exchange, a network of free, community-driven Q&A sites


  1. Good example.

    But i just want to inform that in Difference(first diff) section you use the wrong package names for comparator and comparable.

  2. please alter the package name.... ASAP from Ravi N.joldapke

  3. Yeah good one, Comparable defined in java.lang and Comparator defined in java.util

  4. you need to alter the package name. please do it asap

  5. hi thanks for a brief explanation more thing the first difference is not correct as comparable resides in the java.lang package.