Implementing push

The push operation does three things. It adds the item to arr[size] unless the array is full. In that case, it grows the array first. It also rejects null with an IllegalArgumentException.

@Override
public void push(T item) {
  if (item == null) {
    throw new IllegalArgumentException();
  }
  if (size == arr.length) {
    grow();  // out of room: make the backing array bigger first
  }
  arr[size] = item;  // place the item in the next free slot
  size++;            // the new item is now the top
}

This should look familiar. It is ArrayList’s add, plus the null check.

The grow helper is the same private doubling helper we have used since Chapter 1. I will not implement it here, but you can find it in the code accompanying this chapter.