Member-only story
Effective Java! Consider Implementing Comparable
Today we come to the final chapter of this section about methods common to all objects. Unlike the rest of the methods talked about in this section this method is actually not a method on the class Object
. That being said this method does affect the default operations in various other classes thus it is important to understand. The method we are talking about today is compareTo
and it's related interface, Comparable
.
So what is the purpose of the Comparable
interface? It has a purpose in line with Object
's equals
however its purpose is to do order comparisons as well as equality comparisons. When you implement Comparable
you are indicating that there is a natural order to your instances and offers a way to organize them in that way. Once you implement the interface, sorting an array of them is as simple as Arrays.sort(myArray)
.
Given that the natural order can be determined this makes it trivial to keep a sorted collection, search through values, or find maximum and minimum values. For example filling a TreeSet
(which uses the compareTo
method to sort its internal data structure) with String
objects (which implement Comparable
) you end up with an alphabetized list of values. The Comparable
interface provides a lot of value, this is likely why practically all of Java's built in value types implement this interface. If the value class that you are writing has a natural ordering it can be a good idea to implement this interface as well.