在遍历列表时,可能会删除项目。迭代时从列表中删除项目
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()方法?和一个同步类? – arielnmz 2014-09-01 23:25:48
你的问题不清楚给我。任何例子? – 2014-09-01 23:27:19
removeMethod的加强for循环?这会抛出[ConcurrencyModificationExceptionError](http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html) – 2014-09-01 23:27:20