2020/03/15
1. ConcurrentModificationException
我们应该都知道在foreach(语法糖)/迭代器内循环,是不能够使用集合的remove方法的,需要使用迭代器的remove方法.
原因: 以ArrayList举例.
(1) 在ArrayList内部存在modCount++;代码
modCount在源码中的注释:
The number of times this list has been structurally modified. Structural modifications are those that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.
而在内部类class Itr(迭代器模式)中存在以下代码:
int expectedModCount = modCount;
然后在next()方法中存在checkForComodification();
if (modCount != expectedModCount) throw new ConcurrentModificationException();
综上: 根本原因是Collection子类的remove()方法内部只对modCount进行了修改, 而在迭代器内部需要对exceptextedModCount进行检测. 所以会抛出异常
2.