Search code examples
javacollectionscomparatorcomparable

Why do we use Comparator over Comparable apart from the reason that it helps in customised sorting order?


Comparator is used when we want to achieve customised sorting order but that is also possible with Comparable. So why do we use Comparator?


Solution

  • So why do we use Comparator?

    Some of the reasons include:

    • Because Comparable only allows you to define one sort order. Some applications require more than one sort order; e.g. name order versus age order, or name order versus reverse name order.

    • Because you may not be able to customize the type. For example, you can't customise the sort order of String because String is a final class.

    • Because it may be inappropriate to customize the sort order for the class. For example, it may not make sense for the class to have any natural ordering at all.


    Anyway, Comparator provides an alternative to Comparable. You don't have to use it if you don't want to.