final void checkForComodification() {
if?(modCount?!=?expectedModCount)
throw?new?ConcurrentModificationException();
}
即當(dāng)modCount?!=?expectedModCount時(shí)亡问,執(zhí)行next()就會(huì)拋出ConcurrentModificationException
而什么時(shí)候會(huì)造成modCount?!=?expectedModCount呢妈橄?
ArrayList.add()方法锨咙,每執(zhí)行一次都會(huì)modCount++(當(dāng)然刪除就是modCount--),但不改變expectedModCount的值勋又。expectedModCount的值是在構(gòu)建迭代的時(shí)候初始為expectedModCount=modCount的瓢谢。
這就是樓主說(shuō)的在構(gòu)建迭代器之后襟衰,再使用ArrayList.add()方法就造成了modCount?!=?expectedModCount
所以構(gòu)建迭代器后满败,用迭代器來(lái)add和remove就沒(méi)有問(wèn)題肤频。因?yàn)樗鼤?huì)在改變modCount的值之后,又把值賦給了expectedModCount算墨,從而保證modCount=expectedModCount