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 cards can share a rank and still be different cards. The seven of clubs is not the same card as the seven of hearts. So we need suit to be a tiebreaker, in the order Clubs < Diamonds < Hearts < Spades.

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 Character.compare(this.suit, other.suit);
    }
    return Integer.compare(this.rank, other.rank);
  }
}

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.

Solution

Consistency with equals still holds. compareTo returns zero only when both equals calls would return true, and that is still the case here: compareTo returns zero only when the suits match and the ranks match, which is exactly when equals reports the same card.

@Override
public int compareTo(Card other) {
  if (this.suit == other.suit) {
    return Character.compare(this.rank, other.rank);
  }
  return Character.compare(this.suit, other.suit);
}

What changes is the order itself, not its validity. Rank-first order groups all the twos together, then all the threes, and so on, with suit breaking ties within a rank. Suit-first order groups all clubs together, then all diamonds, and so on, with rank breaking ties within a suit. Neither order is more correct than the other. Rank and suit are independent fields, so which one leads is a choice about what the resulting order is useful for, not a correctness question.