ConcurrentModificationException is commonly encountered while making modifications to a list being iterated over. This exception can arise in various scenarios, one of which is when altering an ArrayList using an Iterator.
In the provided code snippet, this issue manifests during an OnTouchEvent event when adding a new Element to the mElements ArrayList:
for (Iterator<Element> it = mElements.iterator(); it.hasNext();){ Element element = it.next(); // ... if(element.cFlag){ mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY)); element.cFlag = false; } }
The ConcurrentModificationException is thrown because the list is being modified (by adding elements) while it is being iterated using the Iterator.
To address this issue, it is recommended to utilize a separate List to store the elements that need to be added during the iteration:
List<Element> thingsToBeAdded = new ArrayList<Element>(); for (Iterator<Element> it = mElements.iterator(); it.hasNext();) { Element element = it.next(); // ... if (element.cFlag) { // Instead of adding elements directly to mElements, add them to thingsToBeAdded thingsToBeAdded.add(new Element("crack", getResources(), (int) touchX, (int) touchY)); element.cFlag = false; } } mElements.addAll(thingsToBeAdded);
By using this approach, modifications to the original list can be deferred until after iterating over the elements, thereby avoiding the ConcurrentModificationException.
The above is the detailed content of How to Avoid ConcurrentModificationException When Adding to an ArrayList During Iteration in Android?. For more information, please follow other related articles on the PHP Chinese website!