[无异常,才正常]关于ConcurrentModificationException异常

<span style="background-color: rgb(255, 255, 255);"><span style="font-family:KaiTi_GB2312;font-size:18px;">今天在温习算法分析的时候,对一个ArrayList进行遍历删除偶数元素的时候,抛出了一个java.util.ConcurrentModificationException异常</span></span>

for (Integer x : list) { //拋出ConcurrentModificationException异常

<span style="font-family:KaiTi_GB2312;font-size:18px;">if (x%2==0) {
list.remove(x);
}
}</span>

查阅网上资料时,发现以下说明

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.(concurrent是同时发生,大概意思是当一个object被同时修改的时候,而且该修改是不允许的,就会报这个异常)

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it(一个线程在修改容器,而另外一个线程在遍历这个容器,这样是不允许的). In general, the results of the iteration are undefined under these circumstances. (这样做的会发生不确定的结果)Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. (有一些容器的迭代器检测到这样的行为,就会抛出这个异常)Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.(这种称作fail-fast迭代器,它们失效的很快而且很干净利落而不是愿意冒发生不确定行为的危险, 大概就是说, 遇到这种情况迭代器自己直接就把自己给失效了)

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. (这种异常不总是在一个object被不同线程同时修改时抛出, 即不是总是抛出这个异常)If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.(当一个线程对一个容器操作的时候, 例如用fail-fast迭代器边遍历边修改这个容器,就是抛出这个异常)


解决办法是修改代码为如下方式:

Iterator<Integer> iterator=list.iterator();
		while (iterator.hasNext()) {
			if (iterator.next()%2==0) {
				iterator.remove();
			}
		}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值