ArrayList中ConcurrentModificationException
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的更多相关文章
- ArrayList删除--------ConcurrentModificationException问题
在做项目中用到List存储数据,在里面做数据操作时候用到了删除.结果抛出ConcurrentModificationException异常.在这里把问题总结一下. 原因: ArrayList进行for ...
- ArrayList中modCount的作用
在ArrayList中有个成员变量modCount,继承于AbstractList. 这个成员变量记录着集合的修改次数,也就每次add或者remove它的值都会加1.这到底有什么用呢? 先看下面一段测 ...
- 为什么阿里巴巴要求谨慎使用ArrayList中的subList方法
GitHub 3.7k Star 的Java工程师成神之路 ,不来了解一下吗? GitHub 3.7k Star 的Java工程师成神之路 ,真的不来了解一下吗? GitHub 3.7k Star 的 ...
- 谨慎使用ArrayList中的subList方法
转自:https://www.toutiao.com/a6705958780460335619/?tt_from=weixin&utm_campaign=client_share&wx ...
- 从`ArrayList`中了解Java的迭代器
目录 什么是迭代器 迭代器的设计意义 ArrayList对迭代器的实现 增强for循环和迭代器 参考链接 什么是迭代器 Java中的迭代器--Iterator是一个位于java.util包下的接口,这 ...
- ArrayList中元素去重问题
如题所示,如果一个ArrayList中包含多个重复元素,该如何去重呢? 思路一以及实现: 声明2个ArrayList,分别为listA与listB ,listA为待去重list ,listB 保存去重 ...
- Java 删除ArrayList中重复元素,保持顺序
// 删除ArrayList中重复元素,保持顺序 public static List<Map<String, Object>> removeDuplicat ...
- ArrayList list = new ArrayList()在这个泛型为Integer的ArrayList中存放一个String类型的对象
java面试要点---ArrayList list = new ArrayList(); 在这个泛型为Integer的ArrayList中存放一个String类型的对象. ArrayList list ...
- 如何使用 Java 删除 ArrayList 中的重复元素
如何使用 Java 删除 ArrayList 中的重复元素 (How to Remove Duplicates from ArrayList in Java) Given an ArrayList w ...
随机推荐
- JS之汉字与Unicode码的相互转化
有时候,我们在给后端传递变量的的值中有汉字,可能由于编码的原因,传递到后端后变为乱码了.所以有时候为了省事或者其它特殊要求的时候,会把传递的汉字转换成Unicode编码后再进行传递. 当然汉字转换成u ...
- jQuery插件之上传文件ajaxfileupload.js源码与使用
在网页应用中,一般会用到上传文件或者图片什么的到服务器,那么可以用ajaxfileupload.js,但是在使用ajaxfileupload.js时候,当服务器返回的json带有&符号的时候, ...
- 【代码笔记】Web-JavaScript-JavaScript 类型转换
一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...
- Android 组件的三种点击事件写法
一.准备工作 1.项目结构 2.布局文件(activity_main.xml) <?xml version="1.0" encoding="utf-8"? ...
- css和HTML布局小技巧
一:水平居中 1. 如下所示,让child在parent中水平居中 <!DOCTYPE html> <html> <head lang="en"> ...
- iOS开发GCD(3)-数据安全
/* 多个线程可能访问同一块资源,造成数据错乱和数据安全问题 为代码添加同步锁(互斥锁) */ -(void)synchronized{ @synchronized(self){ //需要锁住的代码, ...
- JS辨别访问浏览器判断是android还是ios系统
function isIOSOrAndroid() { var browser = { versions: function() { var u = navigator.userAgent, app ...
- Appium+java 模拟键盘输入
功能键 KEYCODE_CALL 拨号键 5 KEYCODE_ENDCALL 挂机键 6 KEYCODE_HOME 按键Home 3 KEYCODE_MENU 菜单键 82 KEYCODE_BAC ...
- Django JsonResponse与HttpResponse重要区别
JsonResponse是HttpResponse的一个子类,是Django提供的用于创建JSON编码类型响应的快捷类.它的默认Content-Type头部设置为application/json,它的 ...
- MongoDB 主从和Replica Set
目前主要的MongoDB高可用架构包含: 主从架构 Replica set副本集方式 sharding分片 注意:使用高可用架构后ips,qps相比单实例都会有一定程度的下降,其中rs下降不是他太明显 ...