Home > Java > javaTutorial > Why Does Modifying an ArrayList During a For-Each Loop Cause a ConcurrentModificationException?

Why Does Modifying an ArrayList During a For-Each Loop Cause a ConcurrentModificationException?

Barbara Streisand
Release: 2024-12-13 08:06:11
Original
925 people have browsed it

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();
}
Copy after login

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();
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template