In computer programming, an iterator is an object that maintains a type of cursor used for processing each element in a list or in another data structure that contains similar items.

Iterators are frequently used in languages like Java; they are crucial in gaming languages such as UnrealScript.

An example usage of an iterator (for java) can be explained here.

Iterator it = list.iterator();
while(it.hasNext()){
  Object spot = it.next();
}

The above example implies that the Object (called list) supports an iterator method. This hypothetical iterator then supplies the methodss hasNext and next that are used for scrolling through the list of items.

The variable spot is a type of cursor marking the current element.

foreach $spot (@list){
   print "$spot\\n";
}

The above example (in perl) shows the same logic, but is not object oriented. Here @list is an Array of items. The iterator is the foreach keyword, and is used to traverse the list.

Each element in the list is represented by the variable $spot the code within the block can then operate on that particular element.

Physically, an iterator can be viewed as a ruler or (other marker, such as a human finger) placed over a paper list. Each entry is "pointed at" by the ruler, to get to the next entry, one would slide the ruler down one line. This implements a type of physical iterator.

One might ask why have iterators when most languages support counting loops?

  • Counting loops are not suited to all data structures, in particular to data structures with no or slow random access, like lists.
  • Iterators often provide a consistent way to iterate on data structures of all kinds, and so their use help make the code more portable, reusable, less sensitive to a change of data structure. (They are heavily used for that purpose by the C++ standard template library).
  • It is common for the number of items in a list to change even while it is being iterated. An iterator can usually be set up to deal with this without the programmer having to take into account all of the various changes that could occur. This has become very necessary in modern object oriented programming, where the interrelationships between objects and the effects of operations may not be obvious - by using an iterator one is isolated from these sorts of consequences.

See Also: Iterator pattern, Iteration