Implement an iterator over a sequence that supports both normal traversal and state recovery.
Design a class RecoverableIterator initialized with an array or list of elements. It must support the following operations:
-
hasNext()
: return whether there is another element to read.
-
next()
: return the next element and advance the iterator.
-
saveState()
: return an opaque snapshot token representing the iterator's current position.
-
restoreState(token)
: restore the iterator to the position captured by a previous snapshot.
Requirements:
-
After restoring a saved state, subsequent calls to
next()
and
hasNext()
must behave exactly as if no operations had happened after that snapshot was taken.
-
Multiple saved states may exist at the same time, and restoring one state must not invalidate the others.
-
The design should be efficient in both time and space.
-
Discuss edge cases, such as restoring the initial state, restoring the end state, and calling
next()
when no elements remain.
As a follow-up, explain how your design would change if the iterator were reading from a stream instead of an in-memory collection.