THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

set.


The set-expression must either evaluate to an array instance, or an object that implements the interface
java.lang.Iterablewhich is the case for all of the collection classes you'll see in Chapter 21. Here's an
example using an array, where we rewrite the average method we showed on page 19:


static double average(int[] values) {
if (values == null || values.length == 0)
throw new IllegalArgumentException();


double sum = 0.0;
for (int val : values)
sum += val;


return sum / values.length;
}


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 statement.


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 object (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:


for (Iterator iter = obj.iterator();
iter.hasNext();
/ no update expression /)
{
Attr attr = iter.next();
System.out.println(attr);
}

Free download pdf