Diff between Comparable and
Comparator
Comparable
mandates implementation of : int compareTo (Object o)
Comparataor
mandates implementation of : int compare (Object o1, Object
o2)
Both
are implemented when it is desired to provide custom sorting.
However,
Comparable defines the natural ordering of all the objects of a class
i.e. it defines sorting order for all the objects of the implementing
class and for all sorting operations.
Whereas,
Comparator is use-per-operation basis i.e. the class implementing
this interface is different from the class whose elements are
required to be sorted and the Comparator object is specified with
every operation. It overrides the natural sorting defined by
compareTo.
compareTo
is called as obj1.compareTo (obj2);
compare()
is called as compare (obj1, obj2);
Collections.reverseOrder()
returns a Comparator<T> which imposes reversal of order.
Example:
|