Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate with for loop or while loop?

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

like image 411
James A. N. Stauffer Avatar asked Sep 19 '08 03:09

James A. N. Stauffer


People also ask

Which is better for loop or while loop?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.

Can you iterate with a while loop?

The “while” loopA single execution of the loop body is called an iteration. The loop in the example above makes three iterations. If i++ was missing from the example above, the loop would repeat (in theory) forever.

Why would someone use a for loop rather than a while loop?

in general a while loop is used if you want an action to repeat itself until a certain condition is met i.e. if statement. An for loop is used when you want to iterate through an object.

Is it better to use for loop instead of while if you are iterating through a sequence?

Answer: yes, for loop is more pythonic choice.


1 Answers

I prefer the for loop because it also sets the scope of the iterator to just the for loop.

like image 161
Lou Franco Avatar answered Sep 28 '22 00:09

Lou Franco