Alex Rivera | Logout

Iterate with for loop or while loop?

Asked 2008-09-19T03:06:18.223
46

I often see code like:

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

but I write that (when Java 1.5 isn't available or for each can't be used) as:

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

because

  • It is 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?

From: http://jamesjava.blogspot.com/2006/04/iterating.html

Edit
Report

4 Answers

1

Not that it probably matters in this case, but Compilers, VMs and CPU's normally have special optimization techniques they user under the hood that will make for loops performance better (and in the near future parallel), in general they don't do that with while loops (because its harder to determine how it's actually going to run). But in most cases code clarity should trump optimization.

answered 2008-09-19T03:30:25.950
0

Either is fine. I use for () myself, and I don't know if there are compile issues. I suspect they both get optimized down to pretty much the same thing.

answered 2008-09-19T03:07:42.773
0

Although both are really fine, I tend to use the first example because it is easier to read.

There are fewer operations happening on each line with the while() loop, making the code easier for someone new to the code to understand what's going on.

That type of construct also allows me to group initializations in a common location (at the top of the method) which also simplifies commenting for me, and conceptualization for someone reading it for the first time.

answered 2008-09-19T03:13:47.783
0

I agree that the for loop should be used whenever possible but sometimes there's more complex logic that controls the iterator in the body of the loop. In that case you have to go with while.

answered 2008-09-19T03:15:47.123

Your Answer