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:

public class Deck {
    private Card[] cards;

    public Deck(int n) {
        this.cards = new Card[n];
    }

    public Card[] getCards() {
        return this.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:

public Deck() {
    this.cards = new Card[52];
    int index = 0;
    for (int suit = 0; suit <= 3; suit++) {
        for (int rank = 1; rank <= 13; rank++) {
            this.cards[index] = new Card(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:

Deck deck = new Deck();

Now that we have a Deck class, ...

Get Think Java, 2nd Edition 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.