Making your Java objects sortable: the Comparable interface
On the previous page, we looked at how to sort 'naturally'
sortable objects in Java such as Strings and Integers.
But supposing we've created our own class to represent some arbitrary object or data
and want to sort instances of that class? Well, Java can still sort a list of
our objects, providing that we tell Java how to order any two instances.
For this, we need implement the Comparable interface.
Implementing Comparable
Let's consider an example of a class that represents a playing card in a normal deck of
cards. For simplicity, the card will have a suit and a number, both represented
by an integer. (In more sophisticated implementations, you might consider using Enums
instead of an integers.) When we order our cards, we firstly want them ordered according to
suit. We'll define a particular order, namely alphabetical order according to
suit name, which in English would be clubs, diamonds, hearts,
spades1. Then within a suit, we want the cards ordered numerically.
public class PlayingCard {
public static final int SUIT_CLUBS = 1;
public static final int SUIT_DIAMONDS = 2;
public static final int SUIT_HEARTS = 3;
public static final int SUIT_SPADES = 4;
...
private int suit;
private int number;
}
We start by making our class implement the Comparable interface. How exactly this
looks depends on whether you're using Java 5 or later (in other words, whether your version
of Java supports generics). The generic version looks like this:
public class PlayingCard implements Comparable<PlayingCard> {
public int compareTo(PlayingCard o) {
...
}
}
whereas the non-generic (pre Java 5) verion looks like this:
public class PlayingCard implements Comparable {
public int compareTo(Object o) {
...
}
}
In the non-generic version, we'll have some extra casting to do, but the logic
will be essentially the same. We need to make the compareTo() method return
an integer that determines the order of two playing cards (this playing
card with respect to the one passed in). On the next page, we look in more detail
at implementing the compareTo() method.
1. For readers whose native language isn't English, the suits in other languages
include French carreaux, pique etc and Spanish corazones/copas,
picas/espadas etc.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.