O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Rolling Your Own Iterator

Problem

You have your own data structure, but you want to publish the data as an Iterator to provide generic access to it You need to write your own Iterator.

Solution

Just implement (or provide an inner class that implements) the Iterator (or Enumeration ) interface.

Discussion

To make data from one part of your program available in a storage-independent way to other parts of the code, generate an Iterator. Here is a short program that constructs, upon request, an Iterator for some data that it is storing, in this case in an array. The Iterator interface has only three methods: hasNext( ) , next( ), and remove( ).

import java.util.*; /** Demonstrate the Iterator interface (new in 1.2). */ public class IterDemo implements Iterator { protected String[] data = { "one", "two", "three" }; protected int index = 0; /** Returns true if not at the end, i.e., if next( ) will return * an element. Returns false if next( ) will throw an exception. */ public boolean hasNext( ) { return (index < data.length); } /** Returns the next element from the data */ public Object next( ) { if (index >= data.length) throw new IndexOutOfBoundsException( "only " + data.length + " elements"); return data[index++]; } /** Remove the object that next( ) just returned. * An Iterator is not required to support this interface, * and we certainly don't. :-) */ public void remove( ) { throw new UnsupportedOperationException( "This demo does not implement the remove method"); } /** Simple ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required