Reputation: 16755
Two questions on iterators
Question 1) Why is an iterator implemented in such a manner that it cannot be reused? Is it achieve memory optimisation?
scala> while (it.hasNext) println(it.next)
1
2
3
4
5
scala> while (it.hasNext) println(it.next)
scala>
Question 2) How is the iterator implemented to achieve this behavior? Is it that the iterator
points to only one element of the collection and if there is a next element then the previous value of the iterator is overwritten? Something like a LinkedList with logic similar to if (node->next != null) node = node->next
Upvotes: 1
Views: 266
Reputation: 140641
Noticed that method hasNext()
? That method tells you when "everything was iterated". Why do you expect the method to return true again, after it told you: "you saw all the elements" before? How should the iterator "know" that you decided to re-visit all (or some?!) entries again?!
The whole point of (most) iterator implementations is: you use it to "iterate" on something in a certain order.
The whole concept focuses on that "iterating in a certain order". Your idea of re-using the same iterator is thus something that doesn't "fit" the underlying idea of iterators.
Of course, you could create your own iterator implementation that allows for "resetting" the iterator. But as said: that would be something that you need to implement yourself.
Upvotes: 3