Home >Java >javaTutorial >How to Avoid ConcurrentModificationException When Removing from an ArrayList During Iteration?

How to Avoid ConcurrentModificationException When Removing from an ArrayList During Iteration?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 08:51:13483browse

How to Avoid ConcurrentModificationException When Removing from an ArrayList During Iteration?

Avoiding "ConcurrentModificationException" When Removing Elements from ArrayList During Iteration

When attempting to remove elements from an ArrayList during iteration, such as the following example:

for (String str : myArrayList) {
    if (someCondition) {
        myArrayList.remove(str);
    }
}

it is likely to encounter a "ConcurrentModificationException." This occurs because the ArrayList is modified during iteration, which violates the fail-fast property.

Solution: Using an Iterator

To avoid this exception, use an Iterator and call the remove() method:

Iterator<String> iter = myArrayList.iterator();

while (iter.hasNext()) {
    String str = iter.next();

    if (someCondition)
        iter.remove();
}

By using an Iterator, the ArrayList's modifications during iteration are handled internally, ensuring that the exception is not thrown.

The above is the detailed content of How to Avoid ConcurrentModificationException When Removing from an ArrayList During Iteration?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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