When to use Comparable and Comparator
Solution 1:
Use Comparable
if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this.
Use Comparator
if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour.
Solution 2:
I would say that an object should implement Comparable if that is the clear natural way to sort the class, and anyone would need to sort the class would generally want to do it that way.
If, however, the sorting was an unusual use of the class, or the sorting only makes sense for a specific use case, then a Comparator is a better option.
Put another way, given the class name, is it clear how a comparable would sort, or do you have to resort to reading the javadoc? If it is the latter, odds are every future sorting use case would require a comparator, at which point the implementation of comparable may slow down users of the class, not speed them up.
Solution 3:
Use Comparable
:
- if the object is in your control.
- if the comparing behaviour is the main comparing behaviour.
Use Comparator
:
- if the object is outside your control and you cannot make them implement
Comparable
. - when you want comparing behaviour different from the default (which is specified by
Comparable
) behaviour.