I get ConcurrentModificationException in the following piece of code
when i running the code it went fine but all of a sudden it throws a exception, i guess its due to the modification of the list, but i’m not sure how to fix it
if (myRulesIncr!=null)
{
Iterator itReceivedRules = myRulesIncr.iterator();
while (itReceivedRules.hasNext())
{
RuleModel currentReceived = (RuleModel) itReceivedRules.next();
if (receivedRulesExisting!=null)
{
Iterator itReceivedRulesExisting = receivedRulesExisting.iterator();
while (itReceivedRulesExisting.hasNext())
{
RuleModel currentExisting = (RuleModel) itReceivedRulesExisting.next();
if(currentExisting.getRuleId().equals(currentReceived.getRuleId()))
{
//TODO:replace the rule else add it.
if(currentReceived.getStatus()!="D")
{
//replace the existing rule with the new one
receivedRulesExisting.remove(currentExisting);
receivedRulesExisting.add(currentReceived);
}
else
{
receivedRulesExisting.remove(currentExisting);
}
}
else
{
//Add the new rule to the existing rules
receivedRulesExisting.add(currentReceived);
}
}
}
}
}
Please help me out in this .
ConcurrentModificationExceptionis thrown when the collection being iterated is modified externally, i.e. not via the iterator. So you need to useIterator.remove()to avoid this exception. Moreover, instead of adding directly to the collection while iterating through it, store the items to be added in a separate collection, then add them afterwards:Note also that I used a generic collection – it is advisable to do so, to ensure type safety and get rid of downcasts like so: