When to use Comparator and Comparable in Java?
In our previous article we have learnt about the differences between Comparator and Comparable, In this post let’s see some best practices and recommendation on when to use Comparator or Comparable in Java:
Please consider the below point if you are about to perform sorting.
1) If the object is sorted by single way then it should implement Comparable interface, for example, let’s assume you have a Student bean class which has name, rank and id as member variable. In this case if you are about to perform sorting only by using id then you can go for Comparable interface.
On the other hand if an Object can be sorted on multiple ways and client is specifying on which parameter sorting should take place than use Comparator interface. For example if you want to sort all the fields in the Student bean class (i.e. sort by name, rank or id) then you should go for Comparator interface.
2) Some time you write code to sort object of a class for which you are not the author, or you don’t have access to code. In these cases Comparator is only way to sort those objects as you cannot implement Comparable.
3) When you use Comparator you can name each implementation with the way you want to sort things, for example if you are writing Comparator to compare two Students based upon their rank then we can name that comparator as RankComparator, on the other hand by using Comparable interface we can’t give unique name to it.