ArrayList 进行for的时候 抛出ConcurrentModificationException
时间: 2023-10-15 20:26:49 浏览: 42
在使用ArrayList进行for循环时,如果在循环过程中对ArrayList进行了结构性修改(比如增加或删除元素),就会抛出ConcurrentModificationException异常。这个异常的出现是因为在使用迭代器进行循环时,迭代器会在循环开始时记录ArrayList的modCount(修改次数)值,当发现在循环过程中modCount的值发生了改变,就会抛出ConcurrentModificationException异常。这是一种安全机制,用于确保迭代过程中不会发生数据结构的并发修改。所以,如果需要在循环过程中对ArrayList进行修改,建议使用Iterator的remove方法进行操作,而不是直接在循环内部使用ArrayList的add或remove方法。另外,如果需要在多线程环境下使用ArrayList,可以考虑使用线程安全的类,比如CopyOnWriteArrayList。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [ArrayList在多线程时抛出ConcurrentModificationException异常的原因和解决方法](https://blog.csdn.net/wpw2000/article/details/115265271)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [ArrayList什么情况会抛出ConcurrentModificationException](https://blog.csdn.net/qq_34681580/article/details/110451389)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]