Search code examples
javacomparatorcomparable

Is there any thing which can be done only by Comparable and Comparator can't achieve the same


As I understand Comparator can do all that comparable does (+more) so, what is the need of having Comparable? Do we have any advantage in keeping Comparable in Java? Give one example such that something can only be done using Comparable and can't be done by using Comparator.


Solution

  • Comparable is there to support the notion of a natural order for a class. Just like a class implements its equality semantics, so it can optionally implement its ordering semantics. These two notions are linked: the natural order should be consistent with equals, so it clearly belongs inside the same class.

    Yes, we could manage without Comparable, at the expense of increased boilerplate where you couldn't even sort integers according to the obvious ordering without explicitly providing an ordering strategy.