bug-gnu-electric
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


From: Adam Megacz
Subject: Iterator-to-Iterable adapter method: best class to put it in?
Date: Sat, 11 Jul 2009 20:20:02 -0700
User-agent: Gnus/5.110006 (No Gnus v0.6) Emacs/21.4 (gnu/linux)

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





reply via email to

[Prev in Thread] Current Thread [Next in Thread]