I need to know how to "reset" LinkedList iterator to its first element.
For example:
LinkedList<String> list;
Iterator iter=list.listIterator;
iter.next();
iter.next();
Over and over again and after many moves of the iterator I need to "reset" the position of iterator. `
I want to ask how I can "reset" my iterator to first element
I know that I can get list iterator of the first element in this way:
iter= list.listIterator(1);
Is this the best solution? or maybe I missed something in Oracle docs?
Iterator has no reset method. To start again at the beginning, just get a new Iterator by calling iterator() again.
This has nothing to do with the position of the iterator. next() picks out and remembers the element at the pointer, then advances the pointer, then returns the remembered element. You're overthinking it. next() returns the next element in the sequence, starting with the first element.
Explanation: To obtain an iterator to the start of the start of the collection we use iterator() method.
You can call listIterator
method again to get an instance of iterator pointing at beginning of list:
iter = list.listIterator();
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