7.3 Iterating over Collections
Iterating over a collection
works in just about the same way as iterating
over an array. The main difference is that you're going to have to add
some type-casting, as the objects within a collection aren't compile-time
determinable, except when using generics (see the next section on Avoiding Unnecessary Typecasts for details on generics and for/in).
7.3.1 How do I do that?
Example 7-1 is a simple program that shows several types of collection
iteration.
Example 7-1. Demonstrating the for/in loop with collections
NOTEThis example is culled from Java in a Nutshell,
package com.oreilly.tiger.ch07;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ForInDemo {
public static void main(String[] args) {
// These are collections we'll iterate over below.
List wordlist = new ArrayList( );
Set wordset = new HashSet( );
// We start with a basic loop over the elements of an array.
// The body of the loop is executed once for each element of args[].
// Each time through one element is assigned to the variable word.
System.out.println("Assigning arguments to lists...");
for(String word : args) {
System.out.print(word + " ");
wordlist.add(word);
wordset.add(word);
}
System.out.println( );
// Iterate through the elements of the List now.
// Since lists have an order, these words should appear as above
System.out.println("Printing words from wordlist " +
"(ordered, with duplicates)...");
for(Object word : wordlist) {
System.out.print((String)word + " ");
}
System.out.println( );
// Do the same for the Set. The loop looks the same but by virtue of
// using a Set, we lose the word order and also discard duplicates.
System.out.println("Printing words from wordset " +
"(unordered, no duplicates)...");
for(Object word : wordset) {
System.out.print((String)word + " ");
}
}
}
Fifth Edition (O'Reilly).NOTEWhen compiling this class, you'll get several warnings from the compiler
because the code doesn't use a typed list, like List<String>.
I'll cover using generics with for/in later in the chapter.This is pretty basic stuff, so I'll save a tree and cut out repetitive discussion.
Here's the output from the program, which should look exactly as
expected:NOTEIf you're using the
build.xml supplied
with the
examples, just
type "ant runch07"
to see this
output.
run-ch07:
[echo] Running Chapter 7 examples from Java 1.5 Tiger: A Developer's
Notebook\n
[echo] Running ForInDemo...
[java] Assigning arguments to lists...
[java] word1 word2 word3 word4 word1
[java] Printing words from wordlist (ordered, with duplicates)...
[java] word1 word2 word3 word4 word1
[java] Printing words from wordset (unordered, no duplicates)...
[java] word4 word1 word3 word2
|