这里foreach指的是 for (int num: nums)这种用法
下面的代码
//BFS
List<Node> current = new ArrayList<>();
List<Node> next = new ArrayList<>();
while (!current.isEmpty()) {
for (Node node : current) {
next.add(node.left); //ommit if not null
next.add(node.right); //ommit if not null
}
current.clear();
current = next; //want to swap current and next, but mistake
}
这段代码运行后会出现ConcurrentModificationException
问题出在将current指向next的object,
在foreach遍历current中,next做了修改,因为current也指向next,所以意味着current也在做修改
而foreach是基于iterator实现的,详细参照
一不小心就让Java开发者踩坑的fail-fast是个什么鬼?
抛出CME的地方是
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
可以看到当modCount != expectedModCount时抛出CME
而看ArrayList的底层代码发现,在add的时候modCount会+1
因此导致了上述问题
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}