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();
                        }
                    }
                }
2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.