Cloning iterators in Java

2020-08-13 06:03发布

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

2条回答
对你真心纯属浪费
2楼-- · 2020-08-13 06:43

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.

查看更多
不美不萌又怎样
3楼-- · 2020-08-13 06:44

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);
查看更多
登录 后发表回答