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 ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.