In addition to using the
Comparable interface, there is another standard interface we can use to compare objects for equality, and inequalities (greater than, or less than): using the
Comparator<T> interface defines only one method,
compare(T a, T b). The method takes 2 objects,
b and determines the relationship of the two objects based on the following return values (which are the same as the
<a href="http://codenuggets.com/2014/06/29/java-comparable-interface/" target="_blank">compareTo()</a> method):
- Negative integer: if
- Positive integer: if
- 0: if
Comparator Comparable Comparison
So what is the difference between Comparable interface and Comparator interface? The
Comparable defines these relationship inside the class of the objects being compared; therefore,
compareTo() method only takes one parameter. In contrast
Comparator is implemented in a separate class. From the interface above, we can see the
compare() method of Comparator interface takes two parameters.
As we mentioned earlier, there are many ways to define order on objects. Take the
Person class that follow for example, we can sort the class based on any of its attributes, such as name or age. When we use Comparable interface, there is only one way to compare objects. With Comparator we can write multiple classes that implement the interface and have different ways to compare
Person object based on situation. The follow code shows this.
Sorting using Comparator
The flexibility of Comparator allow us to sort objects of a class in different ways (e.g. by name, or by age). Sorting methods in both
<a href="http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html" target="_blank">Arrays</a> and
<a href="http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html" target="_blank">Collections</a> class take an additional
Comparator object. The following code first sorts the array of
Person first by name, then by age.