Fandom

Programmer's Wiki

Iterator

410pages on
this wiki
Add New Page
Talk0 Share

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

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.