循环内部修改List抛出ConcurrentModificationException异常

在对List进行迭代时如果对其进行修改,就会抛出ConcurrentModificationException异常。

for (Entity entity : list) {
	if (entity.getExitNum() == null) {
		list.remove(entity);
		continue;
	}
    //...
}

单线程的解决办法:

Iterator<Entity> iterator = list.iterator();
while (iterator.hasNext()) {
	Entity entity = iterator.next();
	if (entity.getExitNum() == null) {
		iterator.remove();
		continue;
	}
    //...
}

 

参考:https://www.cnblogs.com/dolphin0520/p/3933551.html

转载于:https://my.oschina.net/patch/blog/1618233

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用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 ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值