7.2 Iterating over Arrays
for/in loops work with two basic types: arrays and collection classes
(specifically, only collections that can be iterated over, as detailed in
"Making Your Classes Work with for/in"). Arrays
are the easiest to iterate
over using for/in.
7.2.1 How do I do that?
Arrays have their type declared in the initialization statement, as shown
here:
This means that you can set up your looping variable as that type and
int[] int_array = new int[4];
String[] args = new String[10];
float[] float_array = new float[20];
just operate upon that variable:
This is about as easy as it gets. As a nice benefit, you don't have to worry
public void testArrayLooping(PrintStream out) throws IOException {
int[] primes = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
// Print the primes out using a for/in loop
for (int n : primes) {
out.println(n);
}
}
about the number of times to iterate, and that alone is worth getting to
know this loop.
7.2.2 What about...
...iterating over object arrays? No problem at all. Consider the following
code:
This code compiles and runs perfectly.
public void testObjectArrayLooping(PrintStream out) throws IOException {
List[] list_array = new List[3];
list_array[0] = getList( );
list_array[1] = getList( );
list_array[2] = getList( );
for (List l : list_array) {
out.println(l.getClass( ).getName( ));
}
}