Showing posts with label Difference between Comparable and comparator. Show all posts
Showing posts with label Difference between Comparable and comparator. Show all posts

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.
  
Common 
  •  Both are interfaces. 
  •  Both used for sorting purposes. 


Difference 

Comparable
Comparator
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.