I have a LinkedList in Java, an iterator to browse the list and I would like to clone the iterator to do some temporary "look ahead" processing of the list with respect to the position of the original iterator.
I understand that cloning an iterator is not possible in every situation, but is there a way to clone an iterator to a LinkedList (or save and restore its state)?
It would be possible but Sun made sure you can't (by making the class private).
But maybe you can achieve what you want using a listIterator()
instead of a plain iterator()
. A ListIterator
can move in both directions.
With the ListIterator
you can store the index of the next element, and can get a new ListIterator
based on that index.
Something like this (Java 1.5 example):
LinkedList<Integer> list = new LinkedList<Integer>();
ListIterator<Integer> lit = list.listIterator(0);
<<do something here >>
int index = lit.nextIndex();
ListIterator<Integer> litclone = list.listIterator(index);