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.
See also:
- Sorting an ArrayList of objects using a custom sorting order
java - When to use Comparable and Comparator - Stack Overflow
Comparator vs Comparable
Trouble understanding the Comparator Interface and the compare method and compareTo method.
Comparator vs Comparable
What is the most crucial difference between Comparable and Comparator in Java?
What are the advantages of Comparable over Comparator?
What happens if I don't implement Comparable or Comparator for sorting?
Videos
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.
See also:
- Sorting an ArrayList of objects using a custom sorting order
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.
Hi Everyone :) can someone please explain to me what is the difference between Comparator and Comparable ? I mean when should i use one or another? Can i think of it this way : the Comparable's compareTo() defines the standard way of sorting a list (using the 1 arg sort() in Collections) and if i want to compare objects in many different ways i add Comparators to the class and i call the 2 args sort() ? Thanks in advance Melodie