Programmer's Wiki
Advertisement

An iterator or enumerator is an object that traverses through the elements of a collection. Iterators are used to customize the traversal method of a collection.

Iterators commonly have two functions: pointing to the current item in the collection, and modifying the iterator itself so that it points to the next item in the collection.

Operations
  • current item - the current item in the collection
  • next - moves to the next item
  • has next - returns true if the collection has more items
    Note that the next and has next procedures can be combined so that next is a function returning the result of has next.
  • remove (optional) - removes the current item and moves to the next item
  • reset (optional) - resets the iterator (moves to the first item in the collection)

Here is a simple iterator for a linked list:

class linkedlistiterator of t
    current as listnode of t
    head as listnode of t
    new(list as list of t)
         head = list.head
    
    reset()
         current = head
    
    current() as t
         return current.value
    
    next() as boolean
         current = current.next
         return not current is null

Iterators can be created by a collection object itself. Some programming languages generate implicit iterators for some list results. In other programming languages, generators are used to create iterators.

Iterators are commonly used to customize the usage of for each loops. For each loops can be broken down as follows:

for each x in col
    // do something

// -to-

do
    x = iterator.current
    // do something
while iterator.next
Advertisement