for iterator

I've just come across this code:

Iterator myIterator = myArrayList.iterator();
for (; myIterator.hasNext(); ){
    String string = (String) myIterator.next();
    // do stuff
}

Open in new window


Is there a reason for using a for loop as opposed to a while loop?
LVL 1
allelopathAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
Its really personal preference

these days you can simplify it to

for (String string : myArrayList) {
    // do stuff
0
 
ksivananthConnect With a Mentor Commented:
can't think of any... IMO, "while" suits best here!
0
 
for_yanCommented:


type "for loop vs while loop Java" in Google  - tons of links and tons of opinions
0
 
for_yanConnect With a Mentor Commented:
I'd also think that when you don't have known number of iterations but rather logical condition
while is more suitable, when I have number I rather use for - easier to read and understand
0
 
allelopathAuthor Commented:
>>these days you can simplify
ah, that's why it was done. It is old code, probably written before enhanced for loops
0
All Courses

From novice to tech pro — start learning today.