源码:
//Fig. 16.10: DeckOfCards.java
//Card shuffling and dealing with Collections method shuffle.
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
//class to represent a Card in a deck of cards
class CardCN
{
public static enum Face {A, 二, 三, 四, 五, 六,
七, 八, 九, 十, 杰克, 皇后, 国王};
public static enum Suit {梅花, 方块, 红心, 黑桃};
private final Face face;
private final Suit suit;
// constructor
public CardCN(Face face, Suit suit)
{
this.face = face;
this.suit = suit;
}
// return face of the card
public Face getFace()
{
return face;
}
// return suit of Card
public Suit getSuit()
{
return suit;
}
// return String representation of Card
public String toString()
{
return String.format("%s%s",suit,face);
}
} // end class Card
//class DeckOfCards declaration
public class DeckOfCardsCN
{
private List<CardCN> list; // declare List that will store Cards
// set up deck of Cards and shuffle
public DeckOfCardsCN()
{
CardCN[] deck = new CardCN[52];
int count = 0; // number of cards
// populate deck with Card objects
for (CardCN.Suit suit : CardCN.Suit.values())
{
for (CardCN.Face face : CardCN.Face.values())
{
deck[count] = new CardCN(face, suit);
++count;
}
}
list = Arrays.asList(deck); // get List
Collections.shuffle(list); // shuffle deck
} // end DeckOfCards constructor
// output deck
public void printCards()
{
// display 52 cards in two columns
for (int i = 0; i < list.size(); i++)
System.out.printf("%-19s%s", list.get(i),
((i + 1) % 4 == 0) ? "\n" : "");
}
public static void main(String[] args)
{
DeckOfCardsCN cards = new DeckOfCardsCN();
cards.printCards();
}
} // end class DeckOfCards
运行结果(对齐没处理好,暂且这样吧):
PS C:\01.iworkspace\eclipseWorkspace\jhtp_2017\bin> java ch16_genericCollections.DeckOfCardsCN
梅花六 梅花A 黑桃六 红心国王
红心七 方块十 黑桃A 黑桃皇后
黑桃四 梅花国王 方块三 黑桃七
红心六 黑桃二 方块六 梅花二
红心五 红心三 梅花四 方块二
黑桃五 黑桃三 方块五 方块九
方块四 黑桃国王 梅花皇后 梅花八
黑桃九 方块皇后 红心二 黑桃十
梅花三 黑桃杰克 方块杰克 梅花杰克
方块八 红心八 红心A 方块A
梅花七 红心四 红心皇后 黑桃八
红心杰克 梅花五 梅花十 方块国王
梅花九 红心十 红心九 方块七