Java Reference
In-Depth Information
The for statement is read "for each i in values " and each time through
the loop we add the next value, i , to the sum. This is equivalent to a
basic for statement written as follows:
for (int j = 0 ; j < values.length; j++) {
int val = values[j];
sum += val;
}
The advantage of using the for-each loop with arrays is that you don't
have to manually maintain the array index and check the array length.
The disadvantage is that for-each can only loop forwards through a
single array, and only looks at the array elements. If you want to modify
an array element you will need to know what index you are working
with, and that information is not available in the enhanced for state-
ment.
The main motivation behind the enhanced for statement is to make it
more convenient to iterate through collection classes, or more generally
anything that implements the Iterable interface. The Iterable interface
defines a single method iterator that returns an Iterator for that ob-
ject (see " Iteration " on page 571 ) . Recalling the AttributedImpl class we
defined in Chapter 4 , we can define a method to print all the attributes
of an AttributedImpl object:
static void printAttributes(AttributedImpl obj) {
for (Attr attr : obj)
System.out.println(attr);
}
Again we read this as "for each attr in obj " and it is simply a syntactic
shorthand for a more verbose basic for statement that uses the iterator
explicitly:
 
Search WWH ::




Custom Search