/** Here is an alternative implementation of a stack using an ArrayList * in case we'd like to switch. */ import java.util.*; public class ArrayListStack implements StackInterface { private ArrayList list; public ArrayListStack() { list = new ArrayList(); } public void push(Object o) { list.add(o); } public Object pop() { Object victim = peek(); list.remove(list.size() - 1); return victim; } public Object peek() { return list.get(list.size() - 1); } public int size() { return list.size(); } // We want to show the top (end) of the stack on top, so we start the // iterator at the end, at position = size. Note it's not size - 1, // because the position of an iterator is defined to be which element // would be returned if we call next(). // To go backwards thru the list, we call hasPrevious() and previous(). public String toString() { String build = ""; /* for (int i = list.size() - 1; i >= 0; --i) { build += "\t" + list.get(i) + "\n"; } */ ListIterator iter = list.listIterator(list.size()); while (iter.hasPrevious()) build += "\t" + iter.previous() + "\n"; return build; } }