Solution: A Natural Order
If we want to sort a hand, or pick out the highest card, Card needs an order. The obvious choice is to order by rank. Rank alone is not enough, though, because two different cards can share a rank.
Solution
compareTo returns a negative number, zero, or a positive number when this card is less than, equal to, or greater than the other. Compare rank first. When the ranks match, compare the suit.
public class Card implements Comparable<Card> {
// ... fields, constructor, getters, equals, hashCode ...
@Override
public int compareTo(Card other) {
if (this.rank != other.rank) {
return Integer.compare(this.rank, other.rank);
}
return Character.compare(this.suit, other.suit);
}
}
The suit tiebreak keeps compareTo consistent with equals. If we ordered by rank alone, compareTo would return zero for the seven of clubs and the seven of hearts, while equals says they are different cards. That is the same mismatch we avoided in Student by ordering on the same field equals uses. Comparing the suit when the ranks tie fixes that. Now compareTo returns zero only for two cards with the same rank and the same suit. Those are the same two cards that equals reports as equal.