Java Reference
In-Depth Information
}
Directory "TryDeal"
You can see the benefit of the
Comparable<>
interface being a generic type. The
Card
class implements
the
Comparable<Card>
interface, so the
compareTo()
method works with
Card
objects and no cast is
necessary in the operation. The suit first determines the card sequence. If the two cards are of the same
suit, then you compare the face values. To compare
enum
values for equality you use the
equals()
meth-
od. The
Enum<>
class that is the base for all
enum
types implements the
Comparable<>
interface so you
can use the
compareTo()
method to determine the sequencing of
enum
values.
You could represent a hand of cards that is dealt from a deck as an object of type
Hand
. A
Hand
object
needs to accommodate an arbitrary number of cards, depending on the game the hand is intended for.
You can define the
Hand
class using a
Vector<Card>
object to store the cards:
// Class defining a hand of cards
import java.util.Vector;
public class Hand {
// Add a card to the hand
public void add(Card card) {
hand.add(card);
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
boolean first = true;
for(Card card : hand) {
if(first) {
first = false;
} else {
str.append(", ");
}
str.append(card);
}
return str.toString();
}
private Vector<Card> hand = new Vector<>();
// Stores a hand
of cards
}
Directory "TryDeal"
The default constructor generated by the compiler creates a
Hand
object containing an empty
Vector-
<Card>
member,
hand
. The
add()
member adds the
Card
object passed as an argument by adding it to