Categories
Tech

Enumerate, Iterate, Pretty Kate, …

Ever wanted to iterate over some objects using Java’s for each syntax, but the only interface exposed is an Enumeration? I have. And there’s already a way available out of the box.

Ever wanted to iterate over some objects using Java’s for each syntax, but the only interface exposed is an Enumeration? I have.

There’s an exercise in the Head First Design Patterns book that adapts an Enumeration to the Iterable interface. Pretty nifty, so I coded it up and used it in some code at work. Works great!

But then I found this: the list() method of the Collections class. It stuffs all the items in an Enumeration into a List. And it’s been there since Java 1.4! Where in the world have I been?

Anyway, the upshot is that instead of having to use this old drivel

Enumeration<Nargle> nargles = Nargle.getNargles();
while (nargles.hasMoreElements()) { 
  Nargle nargle = nargles.nextElement();
  // do something with nargle
}

You can do this

for (Nargle nargle : Collections.list(Nargle.getNargles())) {
  // do something with nargle
}

Yes, that is a sight better.

One reply on “Enumerate, Iterate, Pretty Kate, …”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.