Iterator-to-Iterable adapter method: best class to put it in?

Adam Megacz <[email protected]> Sat, 11 Jul 2009 20:20:02 -0700
Newsgroups gmane.comp.cad.electric.bugs
Organization Myself
Message-ID <[email protected]>
I see that many of the Electric methods return Iterator<T>'s rather
than Iterable<T>'s.  Unfortunately, this means that they cannot be
used with the Java5 "enhanced for() loop" [*].  To work around this, I
wrote the following polymorphic method:

    /** Turns an Iterator<T> into an Iterable<T> so I can use Java5's enhanced for() */
    public static <T> Iterable<T> i2i(final Iterator<T> iterator) {
        return new Iterable<T>() {
            boolean used = false;
            public Iterator<T> iterator() {
                if (used) throw new RuntimeException("i2i() produces single-use Iterables!");
                used = true;
                return iterator;
            }
        };
    }

Using i2i(), I can write code like this:

   for(ImmutableExport e : i2i(m.getExports(n.nodeId))) {
     // ..
   }

It seems like this i2i() method should go in some sort of central
location rather than being repeated in each class where it is used.
Can you suggest the best place to put it?

Thanks,

  - a

[*] Personally, I wish javac would let you use an Iterator in a for()
    loop... I can't see why that isn't allowed (or static anonymous
    classes, for that matter -- they serialize better)...