A Comparable
should implement exactly one way of comparing. Allowing it to be changed actually breaks the contract of Comparable
, which requires that (to quote the Javadoc) sgn(x.compareTo(y)) == -sgn(y.compareTo(x))
for all x
and y
. If you can change the comparison that individual Fruit
objects use, you can have an object x
that says it's greater than y
, while y
says it's greater than x
, and so on. Imagine if you have a List<Fruit>
containing objects that are each configured to use a different sort order... trying to sort that list would just be chaos and not produce anything useful.
If you want multiple alternative ways of sorting, create Comparator
s implementing each of those ways and expose them to users in some way. Then a single Comparator
can be passed to the sort method (or TreeSet
constructor, or whatever), ensuring that all comparisons use that logic.