Dav*_*ues 3 java iterator concurrentmodification
我在使用Iterator(LinkedList.iterator())对象的Java上遇到了问题.在循环中,我需要将迭代器对象从某个位置移动到列表末尾.
例如:
final Iterator<Transition> it = this.transitions.iterator();
while(it.hasNext()) {
final Transition object = it.next();
if(object.id == 3){
// Move to end of this.transitions list
// without throw ConcurrentModificationException
}
}
Run Code Online (Sandbox Code Playgroud)
由于某些原因,我无法克隆this.transitions.有可能,或者我真的需要使用克隆方法?
编辑:目前,我这样做:
it.remove();
this.transitions.add(object);
Run Code Online (Sandbox Code Playgroud)
但问题只在于第二行.我无法添加itens,它是同一个对象的内部迭代器.:(
您可以保留要添加的第二个元素列表:
final Iterator<Transition> it = this.transitions.iterator();
final List<Transition> tmp = new ArrayList();//using a list will keep the order
while(it.hasNext()) {
final Transition object = it.next();
if(object.id == 3){
it.remove();
tmp.add(object);
}
}
this.transitions.addAll(tmp);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1862 次 |
| 最近记录: |