Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Iterators implemented in Java?

Tags:

java

iterator

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?

like image 548
user263245 Avatar asked Dec 10 '22 17:12

user263245


2 Answers

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.

like image 75
cletus Avatar answered Dec 12 '22 07:12

cletus


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.

like image 30
Thilo Avatar answered Dec 12 '22 06:12

Thilo