Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java- reset list iterator to first element of the list

Tags:

java

iterator

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?

like image 480
Krzysztof Avatar asked Dec 03 '12 18:12

Krzysztof


People also ask

How do I reset my list iterator?

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

Does iterator next return the first element?

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.

Which of the following functions move the iterator to the first element in array?

Explanation: To obtain an iterator to the start of the start of the collection we use iterator() method.


1 Answers

You can call listIterator method again to get an instance of iterator pointing at beginning of list:

iter = list.listIterator(); 
like image 138
anubhava Avatar answered Sep 20 '22 21:09

anubhava