ArrayLists and Iterators
Read this chapter about lists and the useful methods that are available for adding and inserting elements into a list.
18. Enhanced for Loop
Answer:
Iterator <Integer> visitor = primes.iterator() ;
Enhanced for Loop
Enhanced for Loop
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 accesses the String
references in names
and assigns them one-by-one 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.)
The enhanced for loop only visits those cells that are not empty, beginning with cell zero. Since an ArrayList
never has gaps between cells, all occupied cells are visited.
Question 18:
(Review: ) Can primitive types, like
int
anddouble
be added to anArrayList
?