java中两种基本的集合结构ArrayList和LinkedList底层有两种不同的存储方式实现,ArrayList为数组实现,属于顺序存储,LinkedList为链表实现,属于链式存储,在对ArrayList做迭代删除时,会出现ConcurrentModificationException

public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("aa"); Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
list.remove(next);
}
}
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.baicells.linked.list.ListTest.main(ListTest.java:23)

但如果在list再添加一个元素,如bb,此时list.size = 2,上述代码运行结束后,list中只有bb,虽然与预期结果不一致,但并没有出现ConcurrentModificationException,当再次向集合中添加更多元素时,又出现了ConcurrentModificationException,使用的jdk版本为1.8.

ArrayList源码中,方法iterator()返回了Itr对象

 /**
* Returns an iterator over the elements in this list in proper sequence.
*
* <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
*
* @return an iterator over the elements in this list in proper sequence
*/
public Iterator<E> iterator() {
return new Itr();
}

Itr为ArrayList内部类,主要关注hasNext,next,checkForComodification方法

 /**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount; Itr() {} public boolean hasNext() {
return cursor != size;
} @SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
} public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification(); try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
} @Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
} final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

modCount在add和remove时都会执行++操作,这个可在ArrayList源码中找到出处

在Ite类中,将expectedModCount 的大小初始化为modCount,当执行hashNex和nex时,都不会使modCount的值发生变化

当list中只有一个数据时,此时cursor=0,size=1,hasNex返回true,在next方法中校验modCount和expectedModCount是否相等,如果不相等,则抛出并发修改异常,如果相等,对cursor做了+1操作

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}

此时两者是相等的,都为1,然后执行remove操作删除该数据

 public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
} /*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}

remove是对modCount做了++操作,并且对size做了--操作,while循环继续,hasNext,cursor=1,size=0,两者不相等,则进入到循环,执行next操作

此时modCount在上述remove操作时已经做了++操作,expectedModCount的值却没有变化,故modCount和expectedModCount是不相等的,因此抛出ConcurrentModificationException

当输入两个参数时为什么就不会报错了,虽然结果不是预期的清空了集合?

当集合为2时,在第一次删除后,各关键属性值分别为cursor=1,modCount在add两次后变为2,在remove一次后变为3,expectedModCount=2,size在remove后--,变为1,故此时在while循环hasNext中对比cursor!=size,返回false,while循环结束,继续向下走,所以最后集合中剩下了第二次add的结果,第一次add结果被删除,程序也没有出现ConcurrentModificationException异常。

当输入三个参数或者更多时,会怎样?

继续按照上述思路分析,当集合中有三个元素时,在第一次删除后,各关键属性值分别为cursor=1,modCount在add三次后变为3,在remove一次后变为4,expectedModCount=3,size在remove后--,变为2,此时while循环中cursor!=size返回true,进入while循环,next方法中检测到modCount != expectedModCount返回false,则抛出ConcurrentModificationException

当为更多元素时,在第二次进入到next方法后,都将抛出ConcurrentModificationException,只有在数组元素个数为2时,才不会发生ConcurrentModificationException,但结果也不是我们预期的

综上,不要在迭代集合时删除元素,即使是foreach或者普通for循环(普通for循环或者foreach也会造成size--),也不要这么做,这样做可能造成我们意想不到错误。

ArrayList中ConcurrentModificationException的更多相关文章

  1. ArrayList删除--------ConcurrentModificationException问题

    在做项目中用到List存储数据,在里面做数据操作时候用到了删除.结果抛出ConcurrentModificationException异常.在这里把问题总结一下. 原因: ArrayList进行for ...

  2. ArrayList中modCount的作用

    在ArrayList中有个成员变量modCount,继承于AbstractList. 这个成员变量记录着集合的修改次数,也就每次add或者remove它的值都会加1.这到底有什么用呢? 先看下面一段测 ...

  3. 为什么阿里巴巴要求谨慎使用ArrayList中的subList方法

    GitHub 3.7k Star 的Java工程师成神之路 ,不来了解一下吗? GitHub 3.7k Star 的Java工程师成神之路 ,真的不来了解一下吗? GitHub 3.7k Star 的 ...

  4. 谨慎使用ArrayList中的subList方法

    转自:https://www.toutiao.com/a6705958780460335619/?tt_from=weixin&utm_campaign=client_share&wx ...

  5. 从`ArrayList`中了解Java的迭代器

    目录 什么是迭代器 迭代器的设计意义 ArrayList对迭代器的实现 增强for循环和迭代器 参考链接 什么是迭代器 Java中的迭代器--Iterator是一个位于java.util包下的接口,这 ...

  6. ArrayList中元素去重问题

    如题所示,如果一个ArrayList中包含多个重复元素,该如何去重呢? 思路一以及实现: 声明2个ArrayList,分别为listA与listB ,listA为待去重list ,listB 保存去重 ...

  7. Java 删除ArrayList中重复元素,保持顺序

    // 删除ArrayList中重复元素,保持顺序          public static List<Map<String, Object>> removeDuplicat ...

  8. ArrayList list = new ArrayList()在这个泛型为Integer的ArrayList中存放一个String类型的对象

    java面试要点---ArrayList list = new ArrayList(); 在这个泛型为Integer的ArrayList中存放一个String类型的对象. ArrayList list ...

  9. 如何使用 Java 删除 ArrayList 中的重复元素

    如何使用 Java 删除 ArrayList 中的重复元素 (How to Remove Duplicates from ArrayList in Java) Given an ArrayList w ...

随机推荐

  1. 洛谷P1516 青蛙的约会

    题目描述 两只青蛙在网上相识了,它们聊得很开心,于是觉得很有必要见一面.它们很高兴地发现它们住在同一条纬度线上,于是它们约定各自朝西跳,直到碰面为止.可是它们出发之前忘记了一件很重要的事情,既没有问清 ...

  2. MySQL服务无法启动 3534

    1.环境变量配置完成 2.配置文件编辑完成 3.启动服务(启动不成功,错误信息“MySQL服务无法启动 请键入 NET HELPMSG 3534 以便获得更多的帮助”) 错误原因:mysql安装目录下 ...

  3. 判断字符串a和b是否互为旋转词

    旋转词:把字符串str的任意部分移动到后面形成的新字符串叫做字符串str的旋转词. 比如abc的旋转词有 abc,acb,cba,... 判断str1和str2是否互为旋转词,其最优解可以是时间复杂度 ...

  4. Ubuntu快捷键、Ubuntu终端常用命令

    Ubuntu快捷键 0.Ctrl + Alt + t 打开终端,在终端命令行操作 1. Ctrl + W: 关闭当前 Nautilus 窗口 2. Ctrl+T: 在 Nautilus 打开新的 Ta ...

  5. IDEA基于Maven Struts2搭建配置及示例

    1.web.xml加载struts框架即过滤器,要注意struts版本不同过滤器配置也不同. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems ...

  6. ORACLE导入大量数据的两种方式比较

    不管是开发还是测试,工作中经常需要去批量新增测试数据,但是大量数据的新增速度有时候让我们苦不堪言,下面通过两种方式完成oracle数据的批量新增,比较两种方式的效率. 第一种方式:采用工具导入sql文 ...

  7. 使用VSTS的Git进行版本控制(二)——提交保存工作

    使用VSTS的Git进行版本控制(二)--提交保存工作 当对文件进行更改时,Git将在本地仓库中记录更改.可以通过选择变更来提交的对应更改.提交总是针对本地的Git仓库,因此不必担心提交是完美的,或者 ...

  8. SQL 中用户定义函数的使用方法

    --用户定义函数的分类: /* 1.标量函数 2.表值函数 2.1内联表值函数  返回单个SELECT语句, 它没有相关的返回变量和函数体 2.2多语句表值函数  是视图和存储过程的结合 可嵌套 */ ...

  9. RMAN restore fails with ORA-01180: can not create datafile 1

      最近在验证.测试备份有效性时,遇到了"ORA-01180: can not create datafile 1"这个错误,顺便结合metalink的官方文档"RMAN ...

  10. sqlserver中分区函数 partition by与 group by 区别 删除关键字段重复列

    partition  by关键字是分析性函数的一部分,它和聚合函数(如group by)不同的地方在于它能返回一个分组中的多条记录,而聚合函数一般只有一条反映统计值的记录, partition  by ...