Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning iterators in Java

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

like image 602
Enrico Detoma Avatar asked Oct 09 '09 08:10

Enrico Detoma


People also ask

What are the types of cloning in Java?

Cloning in Java can be grouped into two categories: Shallow Cloning. Deep Cloning.

What is cloning in Java?

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.

Can I copy iterator?

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.

Why is cloning needed in Java?

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.


2 Answers

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.

like image 121
Aaron Digulla Avatar answered Oct 02 '22 05:10

Aaron Digulla


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);
like image 24
AMilassin Avatar answered Sep 29 '22 05:09

AMilassin