Why? And what the best way to move iterator items pointer to the first position?
Iterator has no reset method. To start again at the beginning, just get a new Iterator by calling iterator() again.
The sole purpose of an Iterator is to enumerate through a collection. All collections contain the add() method to serve your purpose. There would be no point in adding to an Iterator because the collection may or may not be ordered (in the case of a HashSet ).
ListIterator lets u add an element after the element which it has recently read. As adding an element to a List is a less expensive operation ( because it allows duplicates ) addition is allowed. The iterator does not need to traverse the list back and forth while inserting into a list.
iterators are not reusable; you need to get a fresh Iterator from the Iterable collection each time you want to iterate over the elements.
Why?
Because if you force iterator to have a reset method every iterator has to have a reset method. That gives every iterator writer extra work. Plus some iterators are really hard (or really expensive) to reset, and you wouldn't want users to call reset on them. Iterators over files or streams are good examples.
what the best way to move iterator items pointer to the first position?
Create a new iterator. It's rarely more expensive than the reset.
Once you read a stream, you can't re-read it without opening the source again. That's how streams and iterators work.
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