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)?
Cloning in Java can be grouped into two categories: Shallow Cloning. Deep Cloning.
Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. Using Assignment Operator to create a copy of the reference variable.
You can only iterate an Iterator once. If you need to "reset" it, and recreating the Iterator is expensive (such as reading from a file), you could copy the data into a temporary Collection (such as an ArrayList). But that requires enough memory to hold everything at once.
Importance of clone() method in Java? The clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default, it does field-by-field copy as the Object class doesn't have any idea about the members of the particular class whose objects call this method.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With