Member-only story
Iterators
6 min readJun 3, 2025
Read full story for free if you don’t have medium membership: https://medium.com/acing-the-software-engineer-interview/iterators-4742a60e584d?sk=6d78f50ff05c99ab2bd19e64d6f19e22
We use them in loops. For example, for(int num: nums) in java.
It is helpful in abstraction as the caller does not need to know the underlying data structure.
There are two commonly used methods
- next() -> Moves to the next element. Note that this is an irreversible operation and changes the internal state of the iterator permanently. We are not able to go back in reverse.
- hasNext() -> Check if there is a next element to go to.
Properties
- Only need to know how to get the next element, and we do not need to store the entire data in memory.
Imagine it as iterating a Linked list, where we keep moving from head to the end. As items are consumed, they are discarded and the next element is replaced with it. - Can use it to represent sequences without incurring memory, O(1). For example, if we want to iterate through a range of values.
- Support infinite data.
public class RangeIterator {
private final int max;
private int current;
public RangeIterator(int min, int max) {
this.current = min…