Loops in Java
Currently Java supports while, for, for-each loop constructs, out of the three which would be the preferred looping construct to iterate over an collection.
Iterating a Collection using for while loop would look like this
In the above case the iterator reference has been used outside the while loop, in the while condition and inside the while loop. Since the iterator reference is of no use after the loop, it is always desirable to limit the scope of the references. Hence usage of while loop is not at all preferred as it does not limit or minimize the scope of loop variables.
Iterating a Collection using for loop would look like this
In the above case loop variables have a lesser scope to that of an while loop. This is an acceptable idiom for all the pre -java 1.5 code. Even though they are better than while construct, the problem with this for loop is it is a bit clumsy and provide oppertunities for errors as they are very verbose.
Iterating a Collection using for-each contruct;
The above for each loop removes all the clutter and verbosity of the previous for loops. there is no performance overhead in using for each loop.
Use for each loop wherever possible and stay away from while and for loops.
Iterating a Collection using for while loop would look like this
Iterator it = aCollection.iterator();
while( it.hasNext() ) {
it.next();
}
Iterating a Collection using for loop would look like this
for ( Iterator it=aCollection.iterator(); it.hasNext();) {
it.next();
}
Iterating a Collection using for-each contruct;
for ( Object a: aCollection) {
}
Use for each loop wherever possible and stay away from while and for loops.
Comments
Post a Comment