Making your Java objects sortable: the compareTo method
On the previous page, we saw that to make our objects sortable, we need to
make them implement the Comparable interface.
This means providing a compareTo() method that will define the order of two
instances of a given object. Specifically, our compareTo() method needs to
return an integer as follows:
- a negative number if our object comes before
the one passed in;
- a positive number if our object comes after
the one passed in;
- otherwise, zero (meaning they're equal in terms of ordering).
Note that the magnitude of the number doesn't matter. The aim isn't
to say "how different" the two objects are, just in which direction. So often,
we may as well use -1 and 1 to mean "before" and "after" respectively.
In our example of playing cards, we want to order first by suit and then by
number. So we first consider what number we would return just by comparing the suit.
If this number is not zero, then we can just return that number: if the
suit's different, we don't need to bother comparing the number. So the first part of
our comparison looks as follows:
public class PlayingCard implements Comparable<PlayingCard> {
public int compareTo(PlayingCard o) {
if (this.suit < o.suit) {
return -1;
} else if (this.suit > o.suit) {
return 1;
} else {
// compare number
}
}
}
Now we're left with the cases of cards with an identical suit, in which case we need
to compare the number in a similar manner:
public class PlayingCard implements Comparable<PlayingCard> {
public int compareTo(PlayingCard o) {
if (this.suit < o.suit) {
return -1;
} else if (this.suit > o.suit) {
return 1;
} else {
// suit is identical: compare number
if (this.number < o.number) {
return -1;
} else if (this.number > o.number) {
return 1;
} else {
return 0;
}
}
}
}
Optimising the compareTo() method
The above implementation of compareTo() will work fine. It has the advantage
of being easy to follow. If you write the method this way, you're unlikely to run
into trouble.
The method as it stands has the slight disadvantage that it's not very succinct and
involves a lot of comparisons. In certain circumstances we can reduce
the number of comparisons. On the next page, we'll look at possible
optimisations to the compareTo() method.
We'll also see that care needs to be taken when applying such optimisations.
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.