[英]Move current object on iterator to end of list
我在使用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
}
}
由於某些原因,我無法克隆this.transitions。 有可能,或者我真的需要使用克隆方法?
編輯 :目前,我這樣做:
it.remove();
this.transitions.add(object);
但問題只在於第二行。 我不能添加它,它我是同一個對象的內部迭代器。 :(
您可以保留要添加的第二個元素列表:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.