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 another step toward object-oriented programming by defining a class to represent a deck of cards. And we present algorithms for shuffling and sorting arrays.

The code for this chapter is in and, which are in the directory ch13 in the repository for this book. Instructions for downloading this code are in “Using the Code Examples”.

The Deck Class

The main idea of this chapter is to create a Deck class that encapsulates an array of Cards. The initial class definition looks like this:

public class Deck {
    private Card[] cards;

    public Deck(int n) { = new Card[n];

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. State diagram of an unpopulated Deck object.

We’ll add a second constructor that makes a standard 52-card deck and populates it with Card objects:

public Deck() { = new Card[52];
    int index = 0;
    for (int suit = 0; suit <= 3; suit++) {
        for (int rank = 1; rank <= 13; rank++) {
  [index] = new Card(rank, suit);

This method is similar to the example in “Arrays of Cards”; we just turned it into a constructor. We can now ...

Get Think Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.