By implementing
Comparable
, you allow your class to interoperate with all of the many generic algorithms and collection implementations that depend on this interface. You gain a tremendous amount of power for a small amount of effort. Virtually all of the value classes in the Java platform libraries implement
Joshua Bloch: Effective Java, Item 11
Let’s assume that we have to implement a book catalog, containing a set of books (for example, the result of a search). Suppose we want to sort these books without burdening the database again. If we wish to sort only on one category (for example, sort by title
), then this is quite easy to accomplish, but if we need to sort by title
and price
, it becomes complicated.
We’ll take our existing Book
class and make it implement the Comparable
interface to allow us to use Java’s standard collections functions. We need to add a compareTo()
function for this interface as shown in Listing 7.5: