Java Reference
In-Depth Information
Iterators
An iterator is something that allows you to examine and possibly modify the elements in
a collection in some sequential order. Java formalizes this concept with the two interfaces
Iterator<T>
and
ListIterator<T>
.
TIP: For-Each Loops as Iterators
A for-each loop is not, strictly speaking, an iterator (because, among other things,
it is not an object), but a for-each loop serves the same purpose as an iterator: It lets
you cycle through the elements in a collection. When dealing with collections, you
can often use a for-each loop in place of an iterator, and the for-each loop is usually
simpler and easier to use than an iterator. For example, in Display 16.14 , we have
rewritten the program in Display 16.13 using for-each loops in place of iterators.
Note that we needed to do some extra programming with the variable
last
in order
to simulate
i.remove()
. Sometimes an iterator works best, and sometimes a for-each
loop works best. Many authorities would say that our code would be better if we had
not replaced the first iterator loop in Display 16.13 with a for-each loop.
■
Display 16.14
For-Each Loops as Iterators
(part 1 of 2)
1
import
java.util.HashSet;
2
import
java.util.Iterator;
3
public class
ForEachDemo
4 {
5
public static void
main(String[] args)
6 {
7 HashSet<String> s =
new
HashSet<String>();
8 s.add("health");
9 s.add("love");
10 s.add("money");
11 System.out.println("The set contains:");
12 String last =
null
;
13
for
(String e : s)
14 {
15 last = e;
16 System.out.println(e);
17 }
(continued)