In the previous article, we see how we can define equality in our class and compare two objects using the
equals() method. In this article, we are going to define additional less than and greater than relations in our class using the
Comparable<T> interface defines relative order in our class, which is useful for sorting. For example, let’s say we’re working on a program that keeps a list of books in sorted order by book title. In order to keep the list sorted, we need to know more than just if two books are equal. What we need is which book should come before the other.
The goals of
Comparable is to compare two objects and see if one is less than, greater than, or equal to the other. The interface only has 1 method,
compareTo(), which takes an object as parameter. For objects
b that implements
- Negative integer: if
- Positive integer: if
- 0: if
a is logically less than
b, depends on how
compareTo() is implemented.
The following snippet shows an example
Person class that defines the ordering based only on the person’s age.
The following code creates an array of 3
Person objects and sorts the array using Java’s sorting method.
When to Implement
When should the
Comparable interface be used? It makes sense for a numeric data type to implement this interface since, numeric values usually have a natural ordering. More generally, whenever your class has an natural ordering, it is a good idea to implement this interface, so that objects of your classes can be sorted by Java’s sorting algorithms.