我有这个 java 代码,它迭代对象的 ArrayList 并从中删除一些记录,但我有一个 ConcurrentModificationException,这是我的代码。
for (ServiceWorkFlowStepModel s : svcModel.getServiceModel().getWorkFlowSteps()) {
if (s.getStepOrder().equals(stepIndex + 1)) {
svcModel.getServiceModel().getWorkFlowSteps().remove(s);
}
Iterator<ActivityModel> iter = activities.iterator();
while (iter.hasNext()) {
ActivityModel am = iter.next();
if (am.getComponentModel().getComponenetId().equals(s.getComponentId())) {
iter.remove();
}
}
}
最佳答案
for-each循环是基于迭代器构建的,下面的代码会在迭代时修改您的集合,这就是您收到 ConcurrentModificationException 的原因。
if (s.getStepOrder().equals(stepIndex + 1)) {
svcModel.getServiceModel().getWorkFlowSteps().remove(s);
}
解决此问题的一种方法是使用 iterator
而不是 for-each
并在迭代器上调用 remove()
,就像您在代码的后面部分。
关于java - 使用迭代器时出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18773734/