当线程A迭代访问容器时,如果线程B调用remove()方法,会导致modCount和expectedModCount的值不一致,从而使checkForComodification方法抛出ConcurrentModificationException异常。
public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }
除了for-each循环,还有些方法会间接地迭代容器:toString()、hashCode()、equals()(容器作为另一个容器的键时会调用hashCode和equals)、containsAll、removeAll、retainAll等方法,以及把容器作为参数作为构造函数。