When I use an Iterator of Object I use a while loop (as written in every book learning Java, as Thinking in Java of Bruce Eckel):
Iterator it=... while(it.hasNext()){ //... }
but sometime i saw than instead somebody use the for loop:
Iterator it=... for (Iterator it=...; it.hasNext();){ //... }
I don’t’ understand this choice:
- I use the for loop when I have a collection with ordinal sequence (as array) or with a special rule for the step (declared generally as a simple increment
counter++). - I use the while loop when the loop finishes with I have’nt this constraints but only a logic condition for exit.
It’s a question of style-coding without other cause or it exists some other logic (performance, for example) that I don’t’ know?
Thanks for every feedback
The correct syntax for the for loop is:
(The preceding declaration in your code is superfluous, as well as the extra semicolon in the for loop heading.)
Whether you use this syntax or the
whileloop is a matter of taste, both translate to exactly the same. The generic syntax of the for loop is:which is equivalent to:
Edit: Actually, the above two forms are not entirely equivalent, if (as in the question) the variable is declared with the init statement. In this case, there will be a difference in the scope of the iterator variable. With the for loop, the scope is limited to the loop itself, in the case of the while loop, however, the scope extends to the end of the enclosing block (no big surprise, since the declaration is outside the loop).
Also, as others have pointed out, in newer versions of Java, there is a shorthand notation for the for loop:
can be written as:
With this form, you of course lose the direct reference to the iterator, which is necessary, for example, if you want to delete items from the collection while iterating.