Iterators

The purpose of the iterator is to provide a mean to sequentially access items of a collection, without exposing the internal structure of the collection.

.Net

In .Net, the iterator is implemented through the IEnumerator interface. The interface a MoveNext method, that must be called first as the property Current is not initially set. The last method, Reset, simply resets the enumerator to its current state.

Although the iterator is an object, c# provides a simpler way to implement an iterator, through the yield keywords. When a method returns an IEnumerable (a factory of enumerators) or an IEnumerator, the compiler generate a state machine object, using the yield return and yield break to store the Current item and to implement the MoveNext. It is worth noting that the Reset method of the generated enumerator is not implemented.

Java

In Java, the iterator interface provides a hasNext method to determine whether to call the next method to retrieve the value and move forward, or not. The is also a remove method, to remove the current item from the underlying collection. Eventhough the implementation of this method is optional, I truly believe it does not belong here.

It is interresting that the iterator just returns the value then move, and does not keep it.

c++

In c++, containers provide iterators. But, while the other implementations know when the iteration ended, the STL iterators don't. Basically, the iterator is considered as an abstraction of a pointer to an array of items. Therefore, as long as you did not reach the end of the array, you keep going. The advantage is that you iterator until you reach a specific position but this implementation is not composable while the .Net and Java are.

Boost attempt to make a "filtered" iterator, kind of a Where extension in .Net, is not DRY. You have to instantiate two iterators with the predicate: the begin and the end.

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.