Java: reset ListIterator?

I need to go through LinkedList several times, so that I can use ListIterator .

Is there a way to reset a ListIterator ? or is it better to just create a new one? (but what if I cannot, because I do not have access to the list?)

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

+4
source share
4 answers

When it comes to performance, it is more likely to create a new iterator faster. If you don't have a list, you can use hasPrevious () and previous () to move backward until you place an iterator at the top of the list. Depending on the implementation of the list, you may encounter a corresponding performance impact when moving back through the iterator.

+3
source

It looks like AbstractList.listIterator(int initialPos) is what I want to use for ArrayList, and LinkedList.descendingIterator() is what I want to use for LinkedList, but there seems to be no single method that would be effectively applied to both, and descendingIterator () returns an Iterator, not a ListIterator. get out.

 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()); } } 
+2
source

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

Edit : For the second question that you subsequently edited, look at Collections#reverse() on the list first.

+1
source

If you can just create a new one, which is probably the best choice.

If you cannot, as you go through the list iterator, add each item to the new list. Use this new list to create a listIterator the next time you need it.

+1
source

Source: https://habr.com/ru/post/1299564/


All Articles