🌱 Tim's Dev Wiki

Search IconIcon to open search

Iterators

Last updated September 16, 2022.

An iterator is an object that lets you loop through an iterable, usually by invoking, implicitly or explicitly, a next method.

An iterable is an object containing a collection of items that you can get an iterator from, usually, via a method. Iterables are stateless and have no concept of what element is the ‘current’ element in a traversal – that is what the iterator handles.

Many programming languages give you a for-loop variant that basically serves as syntactic sugar in using looping through the items in an iterable.

# Iterator Design Pattern

The purpose of iterators is to let the user access the elements of a data structure through a consistent interface, regardless of whether they’re iterating through items in a vector, a binary search tree, a graph, a hash map, etc. All these data structures will provide a way for the user to get an iterator from them that can be used in a for loop, for example.