Iterating on non-iterable classes

Posted by Lucio Benfante Fri, 27 Jul 2007 04:42:00 GMT

(You’ll find all the code of this post in Benfante’s Utilities mini-library)

One of the futures I ‘m reappraising is the JDK 5 enhanced for statement.

I still consider it too limited, but it’s very comfortable in the simplest (and maybe common) cases.

But…what if the elements on which you want to iterate are not managed by an Iterable class?

For example, this happens with the XOM library, where the Element.getChildElements returns an instance of the Elements class, wich is neither a Collection, or an Iterable class. So, for iterating on children elements, you have to use the basic for statement:

for (int i=0; i < elements.size(); i++) {
  Element element = elements.get(i);
  // etc...
}

I would like to write simply:

for (Element element: elements) {
  // etc...
}

So I wrote an Iterabletor class that builds a proxy around a class, enhancing it with the Iterable interface.

Now You can write:

Iterable<Element> iterable =
  new Iterabletor<Element>(elements).getIterable();

for (Element element: iterable) {
  // etc...
}
Read more...

Posted in ,  | Tags , , , ,  | 38 comments