Iterator

From CSSEMediaWiki
Revision as of 04:18, 25 July 2009 by JaninaVoigt (Talk | contribs)
Jump to: navigation, search

An Iterator is a way to step over each element in a collection without exposing the collection's underlying representation to clients. In JAVA, it is sometimes quicker to use the for-each loop, but Iterators are still needed in some cases. The Iterator design in JAVA is arguably broken, see Command query separation.

Use When

Use the iterator pattern when:

  • You want to access the contents of a collection sequentially without exposing the collection's underlying representation to clients.
  • You want to support multiple traversals of a collection.
  • You want to provide the same interface for traversing different collections.

Structure

IteratorStructure.png

Examples

A simple use of an Iterator to print out all names in a collection in JAVA:

Collection<String> names = new HashSet<String>();
...
Iterator<String> myIterator = names.iterator();
while(myIterator.hasNext()) {
  String name = myIterator.next();
  System.out.println(name);
}

The for-each loop in JAVA can perform the same task, in a somewhat neater fashion (syntactically):

Collection<String> names = new HashSet<String>();
...
for(String name : names) {
  System.out.println(name);
}

However, consider the following example:

Collection<String> names = new HashSet<String>();
...
public void removeNames(String lastName) {
  for(String name : names) {
    if(name > lastName)
      names.remove(name);
  }
}

This valid looking code will throw a ConcurrentModificationException, as directly removing an element from a collection while stepping through the collection could cause the code to "get lost". In this example, an Iterator should be used:

Collection<String> names = new HashSet<String>();
...
public void removeNames(String lastName) {
  Iterator<String> myIterator = names.iterator();
  while(myIterator.hasNext()) {
    String name = myIterator.next();
    if(name > lastName)
      myIterator.remove();
  }
}


Personal tools