【发布时间】:2014-10-26 03:50:36
【问题描述】:
在遍历列表时,可能会删除一个项目。
private void removeMethod(Object remObj){
Iterator<?> it = list.iterator();
while (it.hasNext()) {
Object curObj= it.next();
if (curObj == remObj) {
it.remove();
break;
}
}
}
当上面的代码可以发生在另一个循环中时,就会出现问题,该循环正在积极地迭代原始列表。
private void performChecks(){
for(Object obj : list){
//perform series of checks, which could result in removeMethod
//being called on a different object in the list, not the current one
}
}
如何在遍历列表时从列表中删除未知对象?
示例
我有一个监听器对象列表。在通知侦听器事件时,可能不再需要其他侦听器。
【问题讨论】:
-
您是否尝试过使用增强的 for 循环和 .remove() 方法?还有同步课程?
-
你的问题我不清楚。有什么例子吗?
-
removeMethod 的增强 for 循环?那会抛出一个ConcurrencyModificationExceptionError
-
添加示例@BoratSagdiyev
-
@Mr_Skid_Marks 您能否添加一个示例以便我们生成您的问题?
标签: java list concurrency iterator