public class BoundedStack { private Object[] s; private int sp; public BoundedStack(int size){ s = new Object[size]; sp = 0; } public void push(Object entry){ if(sp == s.length) throw new IndexOutOfBoundsException("Stack full"); s[sp++] = entry; } public void pop(){ checkNotEmpty(); s[--sp] = null; // --sp; is a slower alternative to the above line. // It does less but leaves more data reachable, slowing garbage collection. } private void checkNotEmpty() { if(sp == 0) throw new IndexOutOfBoundsException("Stack empty"); } public Object top(){ checkNotEmpty(); return s[sp-1]; } }