The first of the two you specify is a classic C for
loop. This gives the programmer control over the iteration criteria and allows for three operations: the initialization; the loop test ; the increment expression. Though it is used often to incrementally repeat for a set number of attempts, as in yor example:
for (int i=0; i < N : i++)
There are many more instances in code where the for
was use to iterate over collections:
for (Iterator iter = myList.iterator(); iter.hasNext();)
To aleviate the boilerplating of the second type (where the third clause was often unused), and to compliment the Generics introduced in Java 1.5, the second of your two examples - the enhanced for loop, or the for-each loop
- was introduced.
The second is used with arrays and Generic collections. See this documentation. It allows you to iterate over a generic collection, where you know the type of the Collection
, without having to cast the result of the Iterator.next()
to a known type.
Compare:
for(Iterator iter = myList.iterator; iter.hasNext() ; ) {
String myStr = (String) iter.next();
//...do something with myStr
}
with
for (String myStr : myList) {
//...do something with myStr
}
This 'new style' for loop can be used with arrays as well:
String[] strArray= ...
for (String myStr : strArray) {
//...do something with myStr
}