在增强for循环中删除list中的元素报错
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at com.wfbql.test.SetTest.main(SetTest.java:12)
冷静的思考为什么在增强for中就会报错呢?
必须深入源码
报错的原因是由于 modCount和expectedModCount 不相等
那modCount和expectedModCount 是干什么的呢?
创建List的时候会自动创建这两个变量 , expectedModCount的初值为modCount , modCount和expectedModCount是用于表示修改次数的,其中modCount表示集合的修改次数,这其中包括了调用集合本身的add方法等修改方法时进行的修改和调用集合迭代器的修改方法进行的修改。而expectedModCount则是表示迭代器对集合进行修改的次数
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
通过 modCount和expectedModCount 了解到
当我们使用增强的for循环时 遍历的同时修改了ArrayList 中的内容, 由于ArrayList 是非线程安全的,所有报错