Make delicious recipes!

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:






Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal