[英]ConcurrentModificationException when using iterators
I have this java code that iterates over ArrayList of objects and remove some records from it, but I have a ConcurrentModificationException, here is my code. 我有这个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 loop is built on iterators, below code modifies your collection while iterating, which is why you are getting ConcurrentModificationException. for-each循环是基于迭代器构建的,下面的代码在迭代时修改了您的集合,这就是为什么您要获取ConcurrentModificationException的原因。
if (s.getStepOrder().equals(stepIndex + 1)) {
svcModel.getServiceModel().getWorkFlowSteps().remove(s);
}
One approach to solve this issue would be use iterator
instead of for-each
and call remove()
on iterator like you did in later section of your code. 解决此问题的一种方法是使用
iterator
代替for-each
并在迭代器上调用remove()
,就像您在代码后面的部分中所做的那样。
The problem I guess is not in the iterators, but it's in the if block: 我猜这个问题不在迭代器中,而是在if块中:
if (s.getStepOrder().equals(stepIndex + 1)) {
svcModel.getServiceModel().getWorkFlowSteps().remove(s);
}
If your method svcModel.getServiceModel().getWorkFlowSteps()
returned a reference to the same container (I mean, if you didn't return a defensive copy of list
or whatever it is from that method), then you are actually modifying the same container you are iterating upon, though with a different reference. 如果您的方法
svcModel.getServiceModel().getWorkFlowSteps()
返回了对同一容器的引用(我的意思是,如果您没有返回list
的防御性副本或该方法的任何内容),那么您实际上是在修改相同的容器您正在使用的容器,尽管使用了其他参考。 That is why you get that exception. 这就是为什么您得到该例外。
So, you should also change the outer loop to using iterators . 因此,您还应该将外部循环更改为使用迭代器 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.