Creating a Peekable Stack Iterator
If the PeekableStack class is to be used with Java's new "for each" construct, then you must create a "Java Standard" iterator. The implementation for a PeekableStackIterator class is shown in
Listing 3.
In
Listing 3, the iterator does not actually change the value of the stack in any way; instead, the iterator keeps track of its current position in the element list and always returns the next element. Because this information is stored in the iteration class itself, it would be possible to have several iterators operating on the same stack.
The following program tests the Peekable stack.
package com.heatonresearch.examples.collections;
import java.util.*;
public class TestPeekableStack {
public static void main(String args[]) {
PeekableStack<Integer> stack = new
PeekableStack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
for (int i : stack) {
System.out.println(i);
}
System.out.println("Pop 1:" + stack.pop());
System.out.println("Pop 2:" + stack.pop());
System.out.println("Pop 3:" + stack.pop());
}
}
As you can see, three items are added to the stack. Then these three items are displayed using the new "for-each" construct.
for( int i: stack)
{
System.out.println( i );
}
So, you've seen how to successfully implement a collection that supports the new J2SE conventions for both generics and the "for each" construct. As you can see, it's relatively easy to create collections that are compatible with the new constructs in J2SE 5.0 by taking advantage of generics and implementing the appropriate interfaces. You'll find that such collection classes will integrate seamlessly into J2SE 5.0.