How are iterators implemented in Java?

Is an Iterator instance opened in a collection storing the entire collection in memory and accessing a position that is incremented each time next () is called? Or am I missing something?

+4
source share
3 answers

The implementation of Iterator depends on the particular Collection that iterates through. If you look at the source code for JDK, ArrayList and LinkedList , for example, use different iterators.

Remember, Iterator is an interface that is not a specific class, so it just points to a contract not for implementation.

In general, iterators will (depending on the implementation) store a reference to the collection and some kind of index to mark where they are.

+10
source

It depends entirely on the implementation, but in general (for iterators built for collections in memory), Iterator will have a link to the base collection, so yes, it will store it in memory.

Note that this link is most likely not a copy, so iterators check for parallel changes in the collection in which they are created.

+4
source

It completely depends on the object associated with Iterator . Recall that (almost) every Iterator is associated with an Iterable , which we iterate over.

Each Iterable class can define its own Iterator class, which, upon request, returns the next() element.

How does he do it when data is available instantly:

  • It can retrieve each item from a file, from a database, from a library, or any other.
  • It can extract every element from an object that is already in memory.
  • etc.

In case 1, it would probably be useful to store everything in memory, but in case 2, where we already have everything in memory, we could (and really) query this object about the element in the next position.

0
source

Source: https://habr.com/ru/post/1299919/


All Articles