import java.util.*; public class IterStack { protected int data[]; protected int top; public IterStack(int size) { data = new int[size]; top = 0; } public void push(int elem) { data[top++] = elem; } public int pop() { return data[--top]; } public Iterator iterator() { return new StackIterator(); } /// This is an inner class, so it can access any / all data memebrs /// of the containing class private class StackIterator implements Iterator { private int position; public StackIterator() { position = 0; } public boolean hasNext() { return position < top; } public Integer next() { return new Integer(data[position++]); } public void remove() { throw new UnsupportedOperationException(); } } public static void main(String args[]) { IterStack t = new IterStack(30); t.push(3); t.push(4); t.push(5); Iterator it = t.iterator(); while (it.hasNext()) System.out.println(it.next()); } }