Thursday, September 5, 2013

When to use Comparable and Comparator?

By  | September 8, 2013

Programcreek demonstrates examples of using Comparable and Comparator. The next question will be when to use Comparable and Comparator. Here I list two basic rules (actually only the first one is really important):
  1. If there is a natural ordering of the object, then the class should implement Comparable, e.g., integers, strings (generally in the alphabet order), and points. On the other hand, if an object has multiple ways of ordering, then Comparator interface should be used to specify which way of sorting should take place. For example, HDTV in the Programcreek example can either be sorted by size or band name. In such case, Comparator is should be used. Another advantage is that Comparator can specify which parameter to be used for ordering. It then can be self descriptive. Hence, we can have SizeComparator and BandComparator for comparison, respectively.
  2. If you are not able to change the code of the object, which means you cannot implement Comparable, then Comparator is the only way left.
In summary, order of comparison is very important while implementing objects. Requirements may even change during implementing. For example, strings are generally compared alphabetically, but you may need to compare strings on their lengths as well. Therefore, designing of comparison needs to be very careful. In general, implement Comparable for natural order and write a Comparator for other needs.

No comments:

Post a Comment