Iterators in Java


Iterator i = things.iterator();
while(i.hasNext())
{
  Thing t = (Thing)t.next();
  ...
}


for(Iterator i = things.iterator(); i.hasNext(); )
{
  Thing t = (Thing)t.next();
  ...
}


for(Thing t : things)
{
  ...
}
The while form is common-ish, yes? Has the major drawback of leaking i into the surround context. I prefer the second form, the for loop. Some people find the empty expression at the end there unnerving, but they'll just have to suck it up. Most people use for. You agree?

Sun agrees, which is why Java 5 introduced the for each sugar. The for each version is exactly equivalent to the normal for loop. If you get keen and poke around with a disassembler you'll find they compile to exactly the same byte code. It's easier to write though, and easier to read.