Comparable vs Comparators in Java

Comparable and Comparator are two interfaces provided by Java Core API. From their names, we can tell they may be used for comparing stuff in some way. But what exactly are they and what is the difference between them? The following are two examples for answering this question. The simple examples compare two HDTV’s size. How to use Comparable vs. Comparator is obvious after reading the code.

1. Comparable

Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. The class itself must implement the interface in order to be able to compare its instance(s). The method required for implementation is compareTo(). Here is an example:

2. Comparator

In some situations, you may not want to change a class and make it comparable. In such cases, Comparator can be used if you want to compare objects based on certain attributes/fields. For example, 2 persons can be compared based on height or age etc. (this can not be done using comparable.)

The method required to implement is compare(). Now let’s use another way to compare those TV by size. One common use of Comparator is sorting. Both Collections and Arrays classes provide a sort method which use a Comparator.


2 thoughts on “Comparable vs Comparators in Java

Leave a Reply

Your email address will not be published. Required fields are marked *