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!