Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

java - 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

question from:https://stackoverflow.com/questions/99164/iterate-with-for-loop-or-while-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...