How are Iterators implemented in Java?

iterator, java

Solution

The implementation of `Iterator` depends on the particular `Collection` it is iterating. If you look at the JDK source code, `ArrayList` and `LinkedList` for example use different iterators.

Remember `Iterator` is an interface not a concrete class so it simply specifies a contract not an implementation.

Generally speaking iterators will (depending on the implementation) store a reference to the collection and some kind of index to mark where they're up to.

Problem

Does an instance of an Iterator opened on a collection keep the whole collection in memory and access a position that increments every time next() is called? Or am I missing something?

Original source