Tag Archives: comparable

When to use Comparable and Comparator?

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):

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. read more