jav*_*ava 2 java queue exception while-loop
这是我的代码:
Iterator it = queue.iterator();
while(it.hasNext()){
random = randNumber(1,2);
if(random == 1){
queue.poll();
} else {
queue.add("new");
queue.poll();
}
}
Run Code Online (Sandbox Code Playgroud)
它给了我:
Exception in thread "test" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:761)
at java.util.LinkedList$ListItr.next(LinkedList.java:696)
Run Code Online (Sandbox Code Playgroud)
编辑@Jon Skeet:
我想做的是:
通常,在迭代集合时不能修改集合.另一种方法是构建一个单独的"更改"列表,然后在完成迭代后应用它们.
或者,一些集合确实支持这一点ConcurrentLinkedQueue
- 但是大多数都不保证迭代器是否会在迭代时看到所做的更改.(我怀疑这主要是因为它们也是线程安全的,但是我很少看到有关如果在迭代线程中修改集合会发生什么的文档保证.)
编辑:我不确定迭代器是否正确.相反,你可以使用:
while (!queue.isEmpty())
{
// Put logic in here - add, poll etc
}
Run Code Online (Sandbox Code Playgroud)
需要注意的一点是,您发布的代码实际上并不会在任何时候向前移动迭代器 - 它从不调用it.next()
.这是一个强烈的建议,要么你没有完全使用迭代器,要么根本不需要它.
归档时间: |
|
查看次数: |
4254 次 |
最近记录: |