Skip to main content
Engineering LibreTexts

5.1: Decks and Hands

  • Page ID
    15298
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    To implement this game, we need to represent a deck of cards, a discard pile, a draw pile, and a hand for each player. And we need to be able to deal, draw, and discard cards.

    The Deck class from the previous chapter meets some of these requirements, but there are two problems:

    • Hands and piles have different sizes, and their sizes change as the game progresses. Our implementation of Deck uses a Card array, and the size of an array can’t change.
    • It’s not clear that a Deck object is the right way to represent hands and piles. We might want new classes for other collections of cards.

    We can solve the first problem by replacing the Card array with an ArrayList, which is in the java.util package. An ArrayList is a collection, which is an object that contains other objects.

    The Java library provides a variety of collections. For our purposes, ArrayList is a good choice because it provides methods to add and remove elements, and it grows and shrinks automatically.

    To solve the second problem, we can use a language feature called inheritance. We’ll define a new class, CardCollection, to represent a collection of cards. Then we’ll define Deck and Hand as subclasses of CardCollection.

    A subclass is a new class that “extends” an existing class; that is, it has the attributes and methods of the existing class, plus more. We’ll see the details soon, but let’s start with CardCollection:


    This page titled 5.1: Decks and Hands is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?