1

I know that whenever a foreach loop is executed, a new iterator is created, used, and then never used again.

My question is regarding implementing an iterator for a custom class. By convention, should an iterator that is created using the code

Iterator<E> it = new myClass.iterator();

be able to be reused - that is, should my custom iterator class support iterating through the elements more than once for some reason, or is it convention that a user implementing the API of an Iterable class knows to create a new iterator if he/she wants to iterate the elements again?

I hope my question is not too vague; I'm trying to be as specific as possible without violating code-sharing rules of the class that I am taking. I'm most interested in learning about the conventional use of iterators. I figure also in most cases, a user will only need a one-time-use iterator, but wanted to get more insight perhaps as to where a reusable iterator might be used, needed, or required. Thanks!

George C
  • 11
  • 4
  • 2
    How could it possible allow iterating more than once? There is no reset() method in Iterator() that would allow it to restart from the beginning. – JB Nizet Jul 15 '17 at 17:03
  • That's why I asked the question. It didn't seem possible (at least in my implementation) but wanted to make sure I wasn't missing something. I appreciate the explanation in the second sentence despite the tone of the first. – George C Jul 15 '17 at 17:20

3 Answers3

3

As others have pointed out, there is no way to reset an iterator to the start of the collection, so it is not reusable.

That's true not only of java, but also of C#.

You may be thinking that you could create an iterator once as a member of your collection class, and each time a new iterator is requested, you can reset it and return it.

That won't work either, because a caller of your collection class may start an iteration nested within another iteration, so the nested iteration would interfere with the outer iteration.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • Thanks, this is incredibly clear as to why, and +1 for clarifying that it is not limited to just the Java language. Answered my question exactly as I needed to know. – George C Jul 15 '17 at 17:21
1

Since the Iterator interface is moving only in one direction (it supports next() but not previous()) it is not reusable.

For more info: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

Mark H
  • 29
  • 2
0

iterators are not reusable; you need to get a fresh Iterator from the Iterable collection each time you want to iterate over the elements.

for more you can refer bellow stackoverflo answer link: answered by gustafc :

https://stackoverflow.com/a/2599114/7801800

Anshul Sharma
  • 3,432
  • 1
  • 12
  • 17