对比源码和反编译可以看出,都使用iterator进行迭代,差别在于foreach用list.remove(i),iterator用iterator.remove()。
执行在(Integer)iterator.next()抛出并发修改异常(见反编译代码),原因在于,next()中校验了Itr的expectedModCount和ArrayList的modCount需相等。
list.remove(i)使list的modCount++,而iterator中的expectedModCount不变,由此产生差异。
iterator.remove()会将list的modCount赋值给expectedModCount,无差异。