We could use an array (with elements of the generic element type E) to store the elements of the stack.
But an array is fixed size, so it doesn't actually grow or shrink as items are inserted or deleted.
We could keep track of two things:
- Actual size of the array - capacity.
- The number of items logically inserted in the array - sz.
Then,
-
The last item will be at index sz - 1
-
The stack is empty if sz == 0
-
Insertion (push) just stores the item at position sz and then increments sz.
-
Deletion (pop) can copy the value at position sz - 1 to be returned. Then it can set this value to null, decrement sz and returns the copied value.
This can work, but the major problem is the size of the array. The push method cannot do its job if the array is full!
This can be overcome by using an ArrayList instead of an ordinary array since an ArrayList grows as needed when elements are added.