Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why iterator doesn't have any reset method?

Why? And what the best way to move iterator items pointer to the first position?

like image 838
Oleksandr Avatar asked Oct 07 '11 15:10

Oleksandr


People also ask

Can you reset an iterator?

Iterator has no reset method. To start again at the beginning, just get a new Iterator by calling iterator() again.

Why iterator does not have ADD method?

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 ).

Why ListIterator has add () method but iterator doesn't or why add () method is declared in ListIterator and not on iterator?

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.

Can iterators be reused?

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


2 Answers

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.

like image 124
DJClayworth Avatar answered Oct 19 '22 23:10

DJClayworth


Once you read a stream, you can't re-read it without opening the source again. That's how streams and iterators work.

like image 43
duffymo Avatar answered Oct 20 '22 00:10

duffymo