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?
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.
Totally depends on the implementation, but in general (for Iterators constructed for in-memory collections), the Iterator will have a reference to the underlying collection, so yes, it will keep it in memory.
Note that this reference is most likely not a copy, which is why Iterators check for concurrent modifications to the collection they where created for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With