Reputation: 189826
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()
)
Upvotes: 4
Views: 6876
Reputation: 189826
Looks like AbstractList.listIterator(int initialPos)
is what I want to use for an ArrayList, and LinkedList.descendingIterator()
is what I want to use for a LinkedList, but there doesn't appear to be a single method that would apply efficiently to both, and descendingIterator() returns an Iterator, not a ListIterator. drat.
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class ListIteratorTest {
static public void populate(List<Integer> list)
{
for (int i = 0; i < 10; ++i)
{
list.add(i*i);
}
}
static public void main(String[] args)
{
AbstractList<Integer> list = new ArrayList<Integer>();
populate(list);
ListIterator<Integer> it;
System.out.println("List going forwards:");
it = list.listIterator();
while (it.hasNext())
System.out.println(it.next());
System.out.println("List going backwards:");
it = list.listIterator(list.size());
while (it.hasPrevious())
System.out.println(it.previous());
LinkedList<Integer> list2 = new LinkedList<Integer>();
populate(list2);
System.out.println("List going forwards:");
it = list2.listIterator();
while (it.hasNext())
System.out.println(it.next());
System.out.println("List going backwards:");
Iterator<Integer> it2 = list2.descendingIterator();
while (it2.hasNext())
System.out.println(it2.next());
}
}
Upvotes: 2
Reputation: 34323
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.
Upvotes: 3
Reputation: 2499
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.
Upvotes: 1
Reputation: 1109292
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.
Upvotes: 1