Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata