views:

43

answers:

3

I need to traverse a LinkedList a number of times, in a way that suggests using ListIterator.

Is there a way to reset a ListIterator? or is it better to just create a new one? (and what if I can't because I don't have access to the list?)

edit: and is there a way to create a ListIterator that points to the end of the list? (so that hasNext() is false but I can use previous() or hasPrevious())

+1  A: 

Create a new LinkedList based on the obtained ListIterator, so that you can get as many iterators from it as you want.

Edit: as to your second question which you edited in afterwards, consider doing a Collections#reverse() on the list first.

BalusC
ick, I can't reverse the list. phooey. seems like Java's iterators aren't as nice as C's STL iterators.
Jason S
+1  A: 

If you can just create new one that is probably your best bet.

If you cannot, as you are going through the list iterator, add each element to a new list. Use that new list to create the listIterator next time you need it.

Steve g
+1  A: 

When it comes to performance, it's probably faster to create a new iterator. If you don't have the list, you can still use hasPrevious() and previous() to move backwards until you've placed the iterator at the beginning of the list. Depending on the list implementation, you may experience a relevant performance impact navigating backwards through the iterator.

jarnbjo