In this topic, We will discuss about the difference between Comparable and Comparator interface
-
1. Comparable interface resides in java.lang package while Comparator interface resides in java.util package.
2. Using Comparable interface, the class (whose object is being sorted) should implement Comparable interface and also override compareTo() method where as using Comparator interface we can keep the comparison logic separate from the class whose object is being sorted. The custom comparator must implement Comparator interface and also override compare() method.
3. The compareTo(Object o1) method of Comparable interface returns
-
positive- if the current object is greater than o1.
zero- if the curent object equals to o1
negative- if the current is lesser than o1
where as the compare(Object o1, Object o2) method of Comparable interface returns
-
positive- if o1 is greater than o2.
zero- if o1 equals to o2.
negative- if o1 is lesser than o2.
The Comaparator interface is very help full while you need to sort an object from third party framework because in that case you won’t able to modify the class whose object is to be sorted.So you can create custom comparator and pass to Collections.sort() method. It will also increase the maintainability as the sorting logic is separated from the class whose object is to be sorted.