Java基础知识点记录

      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.

 

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容