Iterator <Integer> visitor = primes.iterator() ;
The enhanced for loop (sometimes called a "for each" loop) can
be used with any class that implements the Iterable
interface,
such as
ArrayList
.
Here is the previous program, now written using an enhanced for loop.
import java.util.* ; public class IteratorExampleTwo { public static void main ( String[] args) { ArrayList<String> names = new ArrayList<String>(); names.add( "Amy" ); names.add( "Bob" ); names.add( "Chris" ); names.add( "Deb" ); names.add( "Elaine" ); names.add( "Frank" ); names.add( "Gail" ); names.add( "Hal" ); for ( String nm : names ) System.out.println( nm ); } }
The program does the same thing as the previous program. The enhanced for loop
for ( String nm : names ) System.out.println( nm );
accesses the String
references in names
and
assigns them to nm
.
With an enhanced for loop there is no danger an
index will go out of bounds.
(There is a colon : separating nm
and names
in the above. This might be hard to see in your browser.)
Can primitive types, like int
and double
be
added to an ArrayList
?