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.

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.