java- reset list iterator to first element of the list

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?


Solution 1:

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

iter = list.listIterator();

Solution 2:

Best would be not using LinkedList at all, usually it is slower in all disciplines, and less handy. (When mainly inserting/deleting to the front, especially for big arrays LinkedList is faster)

Use ArrayList, and iterate with

int len = list.size();
for (int i = 0; i < len; i++) {
  Element ele = list.get(i);
}

Reset is trivial, just loop again.
If you insist on using an iterator, then you have to use a new iterator:

iter = list.listIterator();

(I saw only once in my life an advantage of LinkedList: i could loop through whith a while loop and remove the first element)

Solution 3:

This is an alternative solution, but one could argue it doesn't add enough value to make it worth it:

import com.google.common.collect.Iterables;
...
Iterator<String> iter = Iterables.cycle(list).iterator();
if(iter.hasNext()) {
    str = iter.next();
}

Calling hasNext() will reset the iterator cursor to the beginning if it's a the end.