Java Reference
In-Depth Information
the hand vector. You also have implemented a toString() method in the Card class that creates a string
that combines the rank name with the suit name. You use the collection-based for loop to traverse the
cards in the hand and construct a string representation of the complete hand.
It might be good to provide a way to sort the cards in a hand. You could do this by adding a sort()
method to the Hand class:
import java.util.Vector;
import java.util.Collections;
public class Hand {
// Sort the hand
public Hand sort() {
Collections.sort(hand);
return this;
}
// Rest of the class as before...
}
Directory "TryDeal"
The Card class implements the Comparable<> interface, so you can use the static sort() method in the
Collections class to sort the cards in the hand. In order to return the current Hand object after it has
been sorted, the sort() method in the class returns this . This makes the use of the sort() method a
little more convenient, as you see when you put the main() method together.
You might well want to compare hands in general, but this is completely dependent on the context. The
best approach to accommodate this when required is to derive a game-specific class from Hand — a
PokerHand class, for example — and make it implement its own version of the compareTo() method in
the Comparable<> interface.
The last class that you define represents a deck of cards and is able to deal a hand:
import java.util.Stack;
public class CardDeck {
// Create a deck of 52 cards
public CardDeck() {
for(Suit suit : Suit.values())
for(Rank rank : Rank.values())
deck.push(new Card(rank, suit));
}
// Deal a hand
Search WWH ::




Custom Search