Java 将迭代器上的当前对象移动到列表的末尾
我在Java中使用迭代器(LinkedList.Iterator())对象时遇到问题。在循环中,我需要将迭代器对象从列表的某个位置移动到列表的末尾 例如:Java 将迭代器上的当前对象移动到列表的末尾,java,iterator,concurrentmodification,Java,Iterator,Concurrentmodification,我在Java中使用迭代器(LinkedList.Iterator())对象时遇到问题。在循环中,我需要将迭代器对象从列表的某个位置移动到列表的末尾 例如: final Iterator<Transition> it = this.transitions.iterator(); while(it.hasNext()) { final Transition object = it.next(); if(object.id == 3){ // Move t
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
}
}
但问题就在这第二行。我不能添加iten,因为我是同一对象的迭代器(您可以保留第二个要添加的元素列表:
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);
final Iterator it=this.transitions.Iterator();
final List tmp=new ArrayList();//使用列表将保持顺序
while(it.hasNext()){
最终转换对象=it.next();
if(object.id==3){
it.remove();
tmp.add(对象);
}
}
this.transitions.addAll(tmp);
你试过了吗?我很确定你可以毫无问题地修改这个.transitions
,因为你不是直接在上面循环,你使用的是一个迭代器,它基本上是这个.transitions
的克隆。是的。它。remove()
在远程操作上非常有效。但问题是使用this.transitions.add(object)
方法将其添加到列表末尾。哦,你的意思是当你在末尾添加它时,它不会出现在迭代器中
?当我添加到列表末尾时,它会抛出ConcurrentModificationException
,因为this.transition
是“锁定”进行修改。@jonah不,他是说迭代器的快速失败行为阻止了他做他想做的事情是的。这也是我认为的唯一方式。我会在一分钟内接受你的答案。如果存在其他方式(不创建新变量或克隆)将受到欢迎。但只适用于已经比以前更好的工作。呵呵,谢谢
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);