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
Release: 2024-12-19 08:51:13
Original
463 people have browsed it

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

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

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!

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