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
.

- 2,122
- 1
- 18
- 24
-
I implement Comparable when I want default sorting. Comparator for other sorting behaviors. – AppX Dec 08 '14 at 12:57
-
1Think about the pain if some classes like String, Integer wouldn't implement Comparable. You would have to provide a custom comparator each time you want to store them in a TreeSet, use Collections.sort, etc. – Alexis C. Dec 08 '14 at 12:57
-
1@ZouZou Although not necessarily custom: a convention would probably arise that a class has a `Comparator
NATURAL_ORDER` or similar. Not very convenient, though. – Marko Topolnik Dec 08 '14 at 13:05
3 Answers
When a class implements Comparable
you can sort collections of instances of this class without supplying a Comparator
to the sort method. Comparable
can be seen as the "natural" or default ordering of the class, while Comparator
s allow you to define alternative orderings for the class.
For example, having String
implement Comparable<String>
, allows this code :
List<String> strings = ...
Collections.sort (strings);
which is simpler than this code :
List<String> strings = ...
Comparator<String> stringComparator = ...
Collections.sort (strings, stringComparator);

- 387,369
- 54
- 702
- 768
-
-
we can, but how should the developers of string class implement a default ordering of strings without implementing the `compareTo()` method in string class. they can provide a `Comparator
` anywhere else, but this is not so clean as implementing an interface. You maybee should do a bit of research about interfaces than and their use. – kai Dec 08 '14 at 13:22
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.

- 195,646
- 29
- 319
- 436
Comparable
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface. - See more at: http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html#sthash.5ATshjUl.dpuf

- 233
- 2
- 11