Skip to main content

Iterating: for vs. while

Posted by staufferjames on May 23, 2007 at 8:03 AM PDT

I often see code like this (when using Java 1.4 or earlier):

Iterator i = list.iterator();
while(i.hasNext()) {

but I write that as:

for(Iterator i = list.iterator();i.hasNext();) {

* It shorter
* It keeps i in a smaller scope
* It reduces the chance of confusion. (Is "i" used outside the while? Where is "i" declared?)

I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better?

Related Topics >>