Java Reference
In-Depth Information
For the while , do , and for loops, we've shown an example that prints 10 numbers.
The foreach loop can do this too, but it needs a collection to iterate over. In order to
loop 10 times (to print out 10 numbers), we need an array or other collection with
10 elements. Here's code we can use:
// These are the numbers we want to print
int [] primes = new int [] { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 };
// This is the loop that prints them
for ( int n : primes )
System . out . println ( n );
a x
What foreach cannot do
Foreach is different from the while , for , or do loops, because it hides the loop
counter or Iterator from you. This is a very powerful idea, as we'll see when we
discuss lambda expressions, but there are some algorithms that cannot be expressed
very naturally with a foreach loop.
For example, suppose you want to print the elements of an array as a comma-
separated list. To do this, you need to print a comma after every element of the array
except the last, or equivalently, before every element of the array except the first.
With a traditional for loop, the code might look like this:
for ( int i = 0 ; i < words . length ; i ++) {
if ( i > 0 ) System . out . print ( ", " );
System . out . print ( words [ i ]);
This is a very straightforward task, but you simply cannot do it with foreach. The
problem is that the foreach loop doesn't give you a loop counter or any other way to
tell if you're on the first iteration, the last iteration, or somewhere in between.
A similar issue exists when using foreach to iterate through
the elements of a collection. Just as a foreach loop over an
array has no way to obtain the array index of the current ele‐
ment, a foreach loop over a collection has no way to obtain the
Iterator object that is being used to itemize the elements of
the collection.
Here are some other things you cannot do with a foreach style loop:
• Iterate backward through the elements of an array or List .
• Use a single loop counter to access the same-numbered elements of two dis‐
tinct arrays.
• Iterate through the elements of a List using calls to its get() method rather
than calls to its iterator.
Search WWH ::

Custom Search