Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

Back to the Deck Test

Now that Card implements equals, we can rewrite the Deck method contains to take advantage of that fact:

public boolean contains(Rank rank, Suit suit) {
  return cards.contains(new Card(rank, suit));
}

Hmm...what if we choose to put Card objects into a hash-based collection, such as a Set or a HashMap? Try it:

Set<Card> set = new HashSet<Card>();
set.add(new Card(Rank.ace, Suit.spades));
assertTrue(set.contains(new Card(Rank.ace, Suit.spades)));

Next time, we’ll figure out how to get this test to pass by implementing hashCode.

  • + Share This
  • 🔖 Save To Your Account