The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Subdecks

How should we represent a hand or some other subset of a full deck? One good choice is to make a Deck object that has fewer than 52 cards.

We might want a method, subdeck, that takes an array of cards and a range of indices, and that returns a new array of cards that contains the specified subset of the deck:

  public static Deck subdeck (Deck deck, int low, int high) {
    Deck sub = new Deck (high-low+1);

    for (int i = 0; i<sub.cards.length; i++) {
      sub.cards[i] = deck.cards[low+i];
    }
    return sub;
  }

The length of the subdeck is high-low+1 because both the low card and high card are included. This sort of computation can be confusing, and lead to "off-by-one" errors. Drawing a picture is usually the best way to avoid them.

Because we provide an argument with the new command, the contructor that gets invoked will be the first one, which only allocates the array and doesn't allocate any cards. Inside the for loop, the subdeck gets populated with copies of the references from the deck.

The following is a state diagram of a subdeck being created with the parameters low=3 and high=7. The result is a hand with 5 cards that are shared with the original deck; i.e. they are aliased.

I have suggested that aliasing is not generally a good idea, since changes in one subdeck will be reflected in others, which is not the behavior you would expect from real cards and decks. But if the objects in question are immutable, then aliasing can be a reasonable choice. In this case, there is probably no reason ever to change the rank or suit of a card. Instead we will create each card once and then treat it as an immutable object. So for Cards aliasing is a reasonable choice.

As an exercise, write a version of findBisect that takes a subdeck as an argument, rather than a deck and an index range. Which version is more error-prone? Which version do you think is more efficient?



Last Update: 2011-01-24