Concurrent Modification Exception : adding to an ArrayList
I normally use something like this:
for (Element element : new ArrayList<Element>(mElements)) {
...
}
quick, clean and bug-free
another option is to use CopyOnWriteArrayList
ConcurrentModificationException occurs when you modify the list (by adding or removing elements) while traversing a list with Iterator
.
Try
List<Element> thingsToBeAdd = new ArrayList<Element>();
for(Iterator<Element> it = mElements.iterator(); it.hasNext();) {
Element element = it.next();
if(...) {
//irrelevant stuff..
if(element.cFlag){
// mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
thingsToBeAdd.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
element.cFlag = false;
}
}
}
mElements.addAll(thingsToBeAdd );
Also you should consider enhanced for each loop as Jon suggested.
You're not allowed to add an entry to a collection while you're iterating over it.
One option is to create a new List<Element>
for new entries while you're iterating over mElements
, and then add all the new ones to mElement
afterwards (mElements.addAll(newElements)
). Of course, that means you won't have executed the loop body for those new elements - is that a problem?
At the same time, I'd recommend that you update your code to use the enhanced for loop:
for (Element element : mElements) {
...
}