Home >Java >javaTutorial >Why Does Modifying an ArrayList During a For-Each Loop Cause a ConcurrentModificationException?
ConcurrentModificationException for ArrayList
Consider the following code:
private String toString(List<DrugStrength> aDrugStrengthList) { StringBuilder str = new StringBuilder(); for (DrugStrength aDrugStrength : aDrugStrengthList) { if (!aDrugStrength.isValidDrugDescription()) { aDrugStrengthList.remove(aDrugStrength); } } str.append(aDrugStrengthList); if (str.indexOf("]") != -1) { str.insert(str.lastIndexOf("]"), "\n " ); } return str.toString(); }
When executed, this code triggers a ConcurrentModificationException. This exception occurs because modifying the ArrayList while iterating over it using a for each loop is unsafe.
To resolve this issue, replace the for each loop with an iterator loop:
for (Iterator<DrugStrength> it = aDrugStrengthList.iterator(); it.hasNext(); ) { DrugStrength aDrugStrength = it.next(); if (!aDrugStrength.isValidDrugDescription()) { it.remove(); } }
An iterator provides a safe way to remove elements from an ArrayList while iterating over it. It maintains a cursor that keeps track of the current position in the list, ensuring that the removal of an element does not affect the iteration process.
The above is the detailed content of Why Does Modifying an ArrayList During a For-Each Loop Cause a ConcurrentModificationException?. For more information, please follow other related articles on the PHP Chinese website!