Page 455 - Introduction to Programming with Java: A Problem Solving Approach
P. 455

                }
{
bear.display();
10.13 ArrayList Example Using Anonymous Objects and the For-Each Loop 421
For-Each Loop
As mentioned earlier, a for-each loop can be used whenever there’s a need to iterate through all the elements in a collection of data. Here is the for-each loop syntax for an ArrayList:
for (<element-type> <element-name> : <ArrayList-reference-variable>) {
.. .
}
And here is an example for-each loop from Figure 10.29b’s displayInventory method: for (Bear bear : bears)
Note how the for-each loop header matches the above syntax: bears is an ArrayList reference variable, bear is the name of an element in the bears ArrayList, and Bear is the type for each element. It’s legal to choose any name for the element, but, as always, you should choose a descriptive name, like bear in this example. With each iteration of the for-each loop, you use the element’s name to refer to the current element. For example, bear.display() calls the display method for the current bear element.
Are you wondering why the for-each loop is called a for-each loop even though there’s no “each” in the syntax? It’s because mostApepopale gsayo“forPeaDchF” to tEhemnsehlvaes nwhcenererading a for-each loop’s header. For example, in reading displayInventory’s for-each loop, most people would say “For each bear in the bears collection, do the following.”
Note that, as an alternative, you could implement the displayInventory method using a tradi- tional for loop rather than a for-each loop. Here’s an implementation with a traditional for loop:
for (int i=0; i<bears.size(); i++)
{
bears.get(i).display();
The for-each loop implementation is preferred because it is simpler. There’s no need to declare an index variable, and there’s no need to calculate and specify the ArrayList’s first and last index values.
Be aware that you can use the for-each loop for more than just ArrayLists. You can use them for iterating through any collection of elements. More specifically, you can use them for arrays and for any of Java’s collection classes. ArrayList is a collection class, and to learn about the other collection classes, see http://java.sun.com/javase/6/docs/technotes/guides/collections/.
The following code fragment illustrates how to use a for-each loop with a standard array. It prints the numbers in a primes array.
}
}
int[] primes = {1, 2, 3, 5, 7, 11};
for (int p : primes)
{
System.out.println(p);










































































   453   454   455   456   457