以ArrayList为例,它的迭代使用的next方法会调用以下方法
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
modCount是AbstractList(ArrayList的父类)中用来记录集合被修改次数的一个变量,ArrayList中的修改(特指增加和删除)集合元素的方法都会对这个变量进行修改。
expectedModCount是集合在迭代的时候自动生成的变量,它默认是等于modCount的值。当我们在迭代中增加或删除了集合的元素会modCount的值,而expectedModCount未修改,在for的下一次循环中就会抛出异常ConcurrentModificationException。
这里有一个特殊的地方是,如果你在倒数第二次迭代的时候删除集合的元素是不会抛出异常的。
测试代码如下
public class 迭代修改元素测试 {
public static void main(String[] args) {
List<Integer> list = IntStream.rangeClosed(0, 5).boxed().collect(Collectors.toList());
int i = 0;
for (Integer integer : list) {
if (i == list.size() - 2) {
list.remove(4);
}
i++;
System.out.println(integer);
}
}
}
这是因为在倒数第二次遍历时候调用删除方法,增强for默认调用的hasNext()方法会去判断当前的遍历的指针是否等于现在集合中的元素,因为集合的元素被删除了,容量变小了,所以此时的判断是相等的,不会进行下一次遍历,故这样就避开了next方法里面可能会抛出异常的判断。
public boolean hasNext() {
return cursor != size;
}
集合遍历的时候想要删除集合元素可以使用Iterator提供的remove()接口进行删除,因为在remove方法中回去重新将modCount的值赋给expectedModCount,这样就不会发生异常。
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}