import java.util.Iterator; public class IteratorTest { public static void main(String[] args) { // make a stack Stack<Integer> stack = new Stack<Integer>(); // add some numbers stack.push(1); stack.push(2); stack.push(3); stack.push(4); // two options to go though, i.e. to process, all items in the stack // Option 1: enhanced for loop -- *implict/hidden* use of the iterator for (Integer value : stack) { System.out.println(value); // do something with curr value } // Option 2: same effect but with a while loop -- *explicit* use of iterator Iterator<Integer> iter = stack.iterator(); while (iter.hasNext()) { Integer value = iter.next(); // _gives_ value, _moves_ iterator System.out.println(value); // do something with current value } //--------------------------------------------------------------------- // Java will internally translate/rewrite a for-each version (Option 1) // into the version with while loop (Option 2) //--------------------------------------------------------------------- } }