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