Java Reference
In-Depth Information
nameList.add("Joey");
nameList.add("Rachel");
At this point, nameList contains the strings
Jamie
Joey
Rachel
Suppose that the public class SeparateIterator implements the interface Iterator . To create
a separate class iterator for nameList , we create an instance of SeparateIterator , as follows:
Iterator<String> nameIterator = new SeparateIterator<String>(nameList);
This invocation of SeparateIterator 's constructor connects the iterator nameIterator to the list
nameList and positions the iterator just before the first entry in the list. The following sequence of
events demonstrates the iterator methods:
nameIterator.hasNext() returns true because a next entry exists.
nameIterator.next() returns the string Jamie and advances the iterator.
nameIterator.next() returns the string Joey and advances the iterator.
nameIterator.next() returns the string Rachel and advances the iterator.
nameIterator.hasNext() returns false because the iterator is beyond the end of the list.
nameIterator.next() causes a NoSuchElementException .
Figure 15-2 illustrates these events.
FIGURE 15-2
The effect of the iterator methods hasNext and next on a list
Iterator cursor
Jamie
Joey
Rachel
hasNext() returns true
Jamie
Joey
Rachel
next() returns Jamie and
advances the iterator
Jamie
Joey
Rachel
next() returns Joey and
advances the iterator
Jamie
Joey
Rachel
next() returns Rachel and
advances the iterator
Jamie
Joey
Rachel
hasNext() returns false;
next() causes a NoSuchElementException
Search WWH ::




Custom Search