Java Reference
In-Depth Information
The for-each loop is most useful when you simply want to examine each value in
sequence. There are many situations in which a for-each loop is not appropriate. For
example, the following loop would double every value in an array called list :
for (int i = 0; i < list.length; i++) {
list[i] *= 2;
}
Because the loop is changing the array, you can't replace it with a for-each loop:
for (int n : list) {
n *= 2; // changes only n, not the array
}
As the comment indicates, the preceding loop doubles the variable n without
changing the array elements.
In some cases, the for-each loop isn't the most convenient choice even when the
code involves examining each array element in sequence. Consider, for example, the
following loop that prints each array index along with the array value separated by a
tab character:
for (int i = 0; i < data.length; i++) {
System.out.println(i + "\t" + data[i]);
}
A for-each loop could be used to replace the array access:
for (int n : data) {
System.out.println(i + "\t" + n); // not quite legal
}
However, this loop would cause a problem. We want to print the value of i , but we
eliminated i when we converted the array access to a for-each loop. We would have
to add extra code to keep track of the value of i :
// legal but clumsy
int i = 0;
for (int n : data) {
System.out.println(i + "\t" + n);
i++;
}
In this case, the for-each loop doesn't really simplify things, and the original version
is probably clearer.
 
Search WWH ::




Custom Search