Chapter 13. Objects of Arrays
In the previous chapter, we defined a class to represent cards and used an array of Card objects to represent a deck. In this chapter, we take additional steps toward object-oriented programming.
First we define a class to represent a deck of cards. Then we present algorithms for shuffling and sorting decks. Finally, we introduce ArrayList from the Java library and use it to represent collections of cards.
Decks of Cards
Here is the beginning of a Deck class that encapsulates an array of Card objects:
publicclassDeck{privateCard[]cards;publicDeck(intn){this.cards=newCard[n];}publicCard[]getCards(){returnthis.cards;}}
The constructor initializes the instance variable with an array of n cards, but it doesn’t create any Card objects. Figure 13-1 shows what a Deck looks like with no cards.

Figure 13-1. Memory diagram of an unpopulated Deck object
We’ll add another constructor that creates a standard 52-card array and populates it with Card objects:
publicDeck(){this.cards=newCard[52];intindex=0;for(intsuit=0;suit<=3;suit++){for(intrank=1;rank<=13;rank++){this.cards[index]=newCard(rank,suit);index++;}}}
This method is similar to the example in “Arrays of Cards”; we just turned it into a constructor. We can use it to create a complete Deck like this:
Deckdeck=newDeck();
Now that we have a Deck class, ...