The ArrayStack Class

Here is the class, with its fields and constructor:

public class ArrayStack<T> implements Stack<T> {

  private T[] arr;   // the backing array; the top is at index size - 1
  private int size;  // how many items are on the stack

  @SuppressWarnings("unchecked")
  public ArrayStack() {
    arr = (T[]) new Object[10];  // start with room for 10 items
    size = 0;                    // the stack starts empty
  }

  // ... the operations will go here
}

The two fields are exactly the representation we planned: a backing array and a count. Because we decided the top is at the end of the array, the top item is always at index size - 1.

The constructor should look familiar. It uses the same (T[]) new Object[10] cast, with the same @SuppressWarnings, that we used in ArrayList (back in Chapter 2 when it was called DynamicArray).