0

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.

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();
                        }
                    }
                }
Islam
  • 1,647
  • 6
  • 27
  • 40
  • 3
    your problem is the first remove, where you are not using the iterator, but the for each. – dognose Sep 12 '13 at 20:28
  • 1
    Possible duplicate of [Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – Raedwald Mar 28 '16 at 14:49

2 Answers2

4

for-each loop is built on iterators, below code modifies your collection while iterating, which is why you are getting 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.

kosa
  • 65,990
  • 13
  • 130
  • 167
2

The problem I guess is not in the iterators, but it's in the if block:

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. That is why you get that exception.

So, you should also change the outer loop to using iterators.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525