运行以下代码的 for every 循环时出现并发修改异常:
if (entityList.isEmpty()) {
entityList.add(entity);
}
else {
for (Entity e: entityList) {
if (e.getName().equals(p.toString())) {
e.setOccurrence(e.getOccurrence() + 1);
}
else {
entityList.add(entity);
}
}
}
发生这种情况是因为我尝试在同一线程中读取和写入实体列表,对吧? 我不确定如何解决使用 Iterator 对象的问题,只有在删除列表项时发生异常时才有意义。
最佳答案
您得到该异常是因为您正在修改循环内的列表(您正在循环内的列表上调用add
)。
将要添加的实体放入临时列表中,循环结束后将其添加到原始列表中:
if (entityList.isEmpty()) {
entityList.add(entity);
}
else {
List<Entity> tempList = new ArrayList<>();
for (Entity e: entityList) {
if (e.getName().equals(p.toString())) {
e.setOccurrence(e.getOccurrence() + 1);
}
else {
tempList.add(entity);
}
}
entityList.addAll(tempList);
}
关于java - 访问List时并发修改异常如何处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30888017/