pagetop
Javablog
by Java coders, for Java codersRSS

Enumeration and Iterable

November 25th, 2007 by Sam

Why does the aged (and ridiculously verbose) Enumeration not have a sub-interface that implements Iterable… and then make all J2SE classes return the sub-interface so that we could use older classes in the enhanced for loop like this

for (ZipEntry entry : zip.entries()){
  // do stuff
}

It seems like a no-brainer, and wouldn’t break backwards compatibility. Collections.list just doesn’t quite cut it for me (too verbose, and requires creating a list).

for (ZipEntry entry : Collections.list(zip.entries())) {
  // do stuff
}

Update: I somehow managed to miss Stephan’s recent post and Binkley’s older post.


This entry was posted by by Sam on Sunday, November 25th, 2007 at 3:54 pm, and is filed under Enumeration, Iterable, Java, for, legacy, loops. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.



3 comments on “Enumeration and Iterable”

I use

for (ZipEntry entry: iterate(zip.entries())) {
// do stuff
}

with a simple static import. Short, doesn’t create a new list and is less noisy.

http://stephan.reposita.org/archives/2007/11/03/use-java-5-for-with-an-enumertion/

Peace -stephan

— Stephan Schmidt :: stephan@reposita.org Reposita Open Source - Monitor your software development http://www.reposita.org Blog at http://stephan.reposita.org - No signal. No noise.

Thanks Stephan… we have something similar in our codebase, but as soon as you don’t have your utility classes (i.e. coding in another project, possibly an open source hobby project) it is a bit of a pain. For completeness, here’s the code we use:-

public static <T> Iterable<T> iterate(final Enumeration<T> en) {
    final Iterator<T> iterator = new Iterator<T>() {
          public boolean hasNext() {  
              return en.hasMoreElements();  
            }
            public T next() {
              return en.nextElement();  
            }
            public void remove() {
              throw new UnsupportedOperationException();  
            }
    };
    return new Iterable<T>() {
        public Iterator<T> iterator() {
            return iterator;
        }
    };
}

Hi Sam, iterating over Properties with your code like this:


                    for (String propertyName : iterate(model.propertyNames())) {
                        properties.add(new PropertiesTreeData(propertyName,
                                model.getProperty(propertyName), modelFile));
                    }

doesn’t seem to work for me:

Type mismatch: cannot convert from element type capture#1-of ? to String

My mistake?

Leave a comment

Markdown is supported.

To include code snippets in your comment, use

<pre><code># lang java
... code here ...
</code></pre>

or use 4 spaces at the start of the line instead of using code and pre tags.

Comment feed: RSS