Main Page | See live article | Alphabetical index

Iterator

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?

See Also: Iterator pattern, Iteration