Comparators and comparable in Java




Comparators and comparable in Java are two interfaces which are used to implement sorting in Java. It’s often required to sort objects stored in any collection classes like ArrayList, HashSet or in Array and that time we need to use either compare() or compareTo() method defined in java.util.Comparator and java.lang.Comparable


The comparator in Java is defined in java.util package
  • Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
  • Comparator should be used as a utility to sort objects.


Comparable interface in Java is defined in java.lang package
  • The comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
  • Comparable should be provided by default.
  • If any class implement Comparable interface in Java then the collection of that object either List or Array can be sorted automatically by using  Collections.sort() or Arrays.sort() method and object will be sorted based on natural order defined by CompareTo method.


When to use Comparator and Comparable in Java


At last, let’s see some best practices and recommendation on when to use Comparator or Comparable in Java:


  • If there is a natural or default way of sorting Object already exist during the development of Class than use Comparable. This is intuitive and you gave the class name people should be able to guess it correctly like Strings are sorted chronically, Employee can be sorted by Id etc. On the other hand, if an Object can be sorted in multiple ways and client is specifying on which parameter sorting should take place then use Comparator interface. for example, Employee can again be sorted by name, salary or department and clients need an API to do that. Comparator implementation can sort out this problem.


  • Sometimes you write code to sort object of a class for which you are not the original author, or you don't have access to the code. In these cases, you can not implement Comparable and Comparator is the only way to sort those objects.


  • Beware of the fact that How those object will behave if stored in SortedSet or SortedMap like TreeSet and TreeMap. If an object doesn't implement Comparable than while putting them into SortedMap, always provided the corresponding Comparator which can provide sorting logic.


  • Comparator has a distinct advantage of being self-descriptive  for example if you are writing Comparator to compare two Employees based upon salary than name that comparator as SalaryComparator.



Here is a nicely written article on How to override compareTo method in Java


Comments