views:

493

answers:

2

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)?

+6  A: 

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.

Aaron Digulla
That's ok. I'll save the number of steps ahead then go back that number of steps to restore the state.
Enrico Detoma
A: 

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 = ListIlist.listIterator(index);

Imeron
But getting an iterator from the index would mean to browse the list again from the beginning. It seems to me a very expensive way to produce a clone of what is, essentially, a pointer in other languages like C++ with the standard library.
Enrico Detoma