Wednesday, September 17, 2003

Iterators

I've become fascinated by iterators, those small bits of code which turn out an object one at a time. For example, Python has generator comprehensions while Java has iterators and C++ likewise.

Presently I'm adding to my list of Java iterator adaptors, objects which wrap an underlying iterator to produce one with modified behavior. Two excellent examples are FilterIterator which wraps a ListIterator [1] and produces only elements matching a criteria, and ReverseIterator which also wraps a ListIterator to produce the underlying elements in reverse order. I also coded ListIterator versions of each which are bidirectional.

I still have a lot of work, however. C++'s STL is still way ahead of Java's collection classes. I am thinking of putting my work up on SourceForge or some other similar place (perhaps something more Java-specific) under the GPL but have let laziness get the better of me so far. Laziness, Impatience, Hubris [pdf]. What could be better?

[1] FilterIterator wraps a ListIterator rather than an Iterator for a good reason. To properly filter, one needs lookahead which implies the ability to back up the underlying iterator if lookahead failed, hence one needs a reversible iterator with previous(). FilterIterator doesn't just produce the right output, it makes the underlying Iterator behave as if it contained only the filtered elements.

No comments: