Java Reference
In-Depth Information
for ( String word : c ) {
System . out . println ( word );
}
The sense of the code should be clear—it takes the elements of c one at a time and
uses them as a variable in the loop body. More formally, it iterates through the ele‐
ments of an array or collection (or any object that implements java.lang.Itera
ble ). On each iteration it assigns an element of the array or Iterable object to the
loop variable you declare and then executes the loop body, which typically uses the
loop variable to operate on the element. No loop counter or Iterator object is
involved; the foreach loop performs the iteration automatically, and you need not
concern yourself with correct initialization or termination of the loop.
This type of for loop is often referred to as a foreach loop. Let's see how it works.
The following bit of code shows a rewritten (and equivalent) for loop, with the
methods actually shown:
// Iteration with a for loop
for ( Iterator < String > i = c . iterator (); i . hasNext ();) {
System . out . println ( i . next ());
}
The Iterator object, i , is produced from the collection, and used to step through
the collection one item at a time. It can also be used with while loops:
//Iterate through collection elements with a while loop.
//Some implementations (such as lists) guarantee an order of iteration
//Others make no guarantees.
Iterator < String > iterator () = c . iterator ();
while ( iterator . hasNext ()) {
System . out . println ( iterator . next ());
}
Here are some more things you should know about the syntax of the foreach loop:
• As noted earlier, expression must be either an array or an object that imple‐
ments the java.lang.Iterable interface. This type must be known at compile
time so that the compiler can generate appropriate looping code.
• The type of the array or Iterable elements must be assignment-compatible
with the type of the variable declared in the declaration . If you use an Itera
ble object that is not parameterized with an element type, the variable must be
declared as an Object .
• The declaration usually consists of just a type and a variable name, but it may
include a final modifier and any appropriate annotations (see Chapter 4 ).
Using final prevents the loop variable from taking on any value other than the
array or collection element the loop assigns it and serves to emphasize that the
array or collection cannot be altered through the loop variable.
Search WWH ::




Custom Search