Browse DevX
Sign up for e-mail newsletters from DevX


Creating Custom Generic Collections with J2SE 5.0 : Page 3

J2SE 5.0 introduced many additions to the collections API that you need to be aware of to properly implement generic custom collections that work seamlessly with multiple types and the new "for each" construct.

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 
         for (int i : stack) {
         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.

Jeff Heaton is an author, college instructor, and consultant. Jeff is the author of four books and over two dozen journal and magazine articles. Jeff maintains a personal website where he publishes information about artificial intelligence, spider/bot programming, and other topics.
Thanks for your registration, follow us on our social networks to keep up-to-date