集合类单线程也能报ConcurrentModificationException?

在Java的遍历过程中经常会遇到ConcurrentModificationException,中文名称叫并发修改异常,但是单线程怎么可能会出现这种情况呢?

Java中for循环常用的有两种遍历方式。

一种是fori:

for (int i = 0; i < list.size(); i++) {
     System.out.println(list.get(i));
}

另外一种是foreach:

for (String element: list) {
     System.out.println(element);
}

ConcurrentModificationException就出现在后面一种,foreach内部使用的是迭代器遍历,只要类实现了Iterable接口,就可以使用foreach这种遍历方式。

public interface Iterable {

Iterator iterator();

default void forEach(Consumer