Iterator

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
Line 1: Line 1:
 
[[Category:Design Patterns]]
 
[[Category:Design Patterns]]
 +
[[Category:Behavioural Patterns]]
 
An Iterator is a way to step over each element in a collection. 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]].
 
An Iterator is a way to step over each element in a collection. 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]].
  

Revision as of 03:43, 16 July 2009

An Iterator is a way to step over each element in a collection. 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.

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