![]() |
VOOZH | about |
In Java, both Comparable and Comparator interfaces are used for sorting objects. The main difference between Comparable and Comparator is:
In this example, we use the Comparable interface to sort Movies by their release year using compareTo() method.
Movies after sorting by year: Star Wars 8.7 1977 Empire Strikes Back 8.8 1980 Return of the Jedi 8.4 1983
Explanation:
Now, suppose we want to sort movies by their rating and names as well. When we make a collection element comparable (by having it implement Comparable), we get only one chance to implement the compareTo() method. The solution is using Comparator.
In this example, we use Comparator interface to define custom sorting logic to sort movies first by rating and then by name.
Movies sorted by rating: 8.8 Empire Strikes Back 1980 8.7 Star Wars 1977 8.3 Force Awakens 2015 Movies sorted by name: Empire Strikes Back 8.8 1980 Force Awakens 8.3 2015 Star Wars 8.7 1977
Explanation: In the above example, the Comparator interface is used to sort the movies first by rating and then by name. The Rating and NameCompare classes implement custom sorting logic. The Collections.sort() method uses these comparators to sort the list by multiple criteria.
The table below demonstrates the difference between comparable and comparator in Java.
Features | Comparable | Comparator |
|---|---|---|
Definition | It defines natural ordering within the class. | It defines external or custom sorting logic. |
Method | compareTo() | compare() |
Implementation | It is implemented in the class. | It is implemented in a separate class. |
Sorting Criteria | Natural order sorting | Custom order sorting |
Usage | It is used for a single sorting order. | It is used for multiple sorting orders. |