在使用Iterator来迭代遍历List的时候如果修改该List对象,则会报java.util.ConcurrentModificationException异常,下面看一个例子演示:

 package com.others;

 import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList; public class ArrayListTest { public static void main(String[] args) {
List<String> list = new ArrayList<String>();
//CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
Iterator iterator = list.iterator();
while(iterator.hasNext()){
String str = (String) iterator.next();
if(str.equals("c")){
list.remove(str);
}else{
System.out.println(str);
}
}
} }

  结果为:

a
b
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at com.others.ArrayListTest.main(ArrayListTest.java:20)

  当调用list的iterator()方法的时候,返回的是一个Itr对象(实现了Iterator接口):

 public Iterator<E> iterator() {
return new Itr();
}

  我们看一下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; //刚创建迭代对象的时候List的modCount public boolean hasNext() {
return cursor != size;
} @SuppressWarnings("unchecked")
public E next() {
checkForComodification(); //每调用一次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();
}
}
//此方法用来判断创建迭代对象的时候List的modCount与现在List的modCount是否一样,不一样的话就报ConcurrentModificationException异常
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}

  List对象有一个成员变量modCount,它代表该List对象被修改的次数,每对List对象修改一次,modCount都会加1.

  Itr类里有一个成员变量expectedModCount,它的值为创建Itr对象的时候List的modCount值。用此变量来检验在迭代过程中List对象是否被修改了,如果被修改了则抛出java.util.ConcurrentModificationException异常。在每次调用Itr对象的next()方法的时候都会调用checkForComodification()方法进行一次检验,checkForComodification()方法中做的工作就是比较expectedModCount 和modCount的值是否相等,如果不相等,就认为还有其他对象正在对当前的List进行操作,那个就会抛出ConcurrentModificationException异常。

  我们再来分析一下上面那个例子,当例子程序执行到22行的时候,将list对象里面的“c"删除了,同时list对象的modCount值加1,但是Itr对象的expectedModCount没有变,他们肯定是不相等了。等再一次执行next()方法的时候调用了checkForComodification()方法,这时候就抛出异常了。

  我们再将上面那个例子稍微改动一下:将21行改为if(str.equals("d")){,即删除”d"这个元素。运行结果如下:

a

b

c

  这时却没有报异常了,但是“e"却没有输出来,这是为什么呢?原因很简单,我们看到Itr的hashNext()方法:

 public boolean hasNext() {
return cursor != size;
}

  它是通过Itr的对象的cursor与List对象的size值来判断是否还有未迭代的对象,当遍历完“d"的时候cursor=4,删除”d"的时候,List对象的size就会减1,size首先为5,后来变为4,这时候cursor和size是相等的,hasNext()方法返回的是false,就认为遍历结束了,所以删除以后没有进去执行next()方法了,就没有抛出异常了,当然"e"也没有输出来。

  为了避免这种异常,我们可以使用CopyOnWriteArrayList来代替ArrayList,CopyOnWriteArrayList支持并发访问,所以同时进行迭代和修改是没有问题的。

使用迭代器遍历List的时候修改List报ConcurrentModificationException异常原因分析的更多相关文章

  1. 修改List报ConcurrentModificationException异常原因分析

    使用迭代器遍历List的时候修改List报ConcurrentModificationException异常原因分析 在使用Iterator来迭代遍历List的时候如果修改该List对象,则会报jav ...

  2. 使用迭代器遍历List的时候修改List报ConcurrentModificationException异常的解决办法

    为了避免这种异常,我们可以使用CopyOnWriteArrayList来代替ArrayList,CopyOnWriteArrayList支持并发访问,所以同时进行迭代和修改是没有问题的.

  3. 在多线程的情况下是由Iterator遍历修改集合对象,报ConcurrentModificationException()异常的根因分析

    遍历List时抛ConcurrentModificationException异常原理分析     http://www.blogjava.net/houlinyan/archive/2008/04/ ...

  4. 遍历ArrayList时同时修改引发的问题

    看见一篇博客,没有写完整,于是增补了一下: 博客原文:http://www.cnblogs.com/alipayhutu/archive/2012/08/11/2634073.html 注:黄色字体为 ...

  5. Redis Scan迭代器遍历操作原理(一)

    Redis在2.8.0版本新增了众望所归的scan操作,从此再也不用担心敲入了keys*, 然后举起双手看着键盘等待漫长的系统卡死了··· 命令的官方介绍在这里, 中文版由huangz同学细心翻译了, ...

  6. Java集合——遍历集合元素并修改

    Java集合——遍历集合元素并修改 摘要:本文主要总结了遍历集合的方式,以及在遍历时修改集合要注意的问题. 遍历Collection 对List和Set的遍历,有四种方式,下面以ArrayList为例 ...

  7. - 集合 遍历 foreach Iterator 并发修改 ConcurrentModificationException MD

    目录 目录 为什么不能在 foreach 循环里进行元素的 remove/add 操作 背景 foreach 循环 问题重现 fail-fast remove/add 做了什么 正确姿势 直接使用普通 ...

  8. Java List中迭代器遍历

    在java中,List接口从Collection接口中继承了 iterator()函数,返回值是一个T类型的迭代器(泛型),T是List中元素的类型 public class TestListAndI ...

  9. java 迭代器遍历List Set Map

    Iterator接口: 所有实现了Collection接口的容器类都有一个iterator方法用以返回一个实现Iterator接口的对象 Iterator对象称作为迭代器,用以方便的对容器内元素的遍历 ...

随机推荐

  1. Tomcat 报 The valid characters are defined in RFC 7230 and RFC 3986

    问题 24-Mar-2017 23:43:21.300 INFO [http-apr-8001-exec-77] org.apache.coyote.http11.AbstractHttp11Proc ...

  2. Google SRE 读书笔记 扒一扒SRE用的那些工具

    写在前面 最近花了一点时间阅读了<SRE Goolge运维解密>这本书,对于书的内容大家可以看看豆瓣上的介绍.总体而言,这本书是首次比较系统的披露Google内部SRE运作的一些指导思想. ...

  3. poj 1325 Machine Schedule 题解

    Machine Schedule Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 14479   Accepted: 6172 ...

  4. NVelocity语法常用指令

    对变量的引用:$ [ ! ][ { ][ a..z, A..Z ][ a..z, A..Z, 0..9, -, _ ][ } ]. 在NVelocity中,对变量的引用都是以$开头加上变量名称.当使用 ...

  5. Risc-V指令集

    https://riscv.org/specifications/ Risc-V文档包括:用户层指令集文档和特权架构文档,下面这两个文件的官网链接. User-Level ISA Specificat ...

  6. Asp.Net 控件 GridView

    这两天做的作业都得用到visual studio 越来越发现其功能真心强大 前几天Asp.Net做了个界面增删查改的作业(连接数据库),用到了个组件GridView,感觉很强大 在这里小结一下(这里主 ...

  7. [leetcode]Length of Last Word @ Python

    原题地址:https://oj.leetcode.com/problems/length-of-last-word/ 题意: Given a string s consists of upper/lo ...

  8. \r\n 如何转换成utf-8格式的,在jsp页面中正常显示换行

    数据库中存的换行是\r\n,读取到UTF-8编码的JSP 页面上以后,没有换行 在jsp页面显示之前,要进行一下字符转换,将所有\r\n转换成<br>,如下: String result  ...

  9. 揭秘uc浏览器三

    这节我们主要讨论收藏与历史记录页面的边边角角. 首先,看看他的最终的效果图了: 照例了,我们先看看他的布局文件: <!-- tab布局文件 --> <TabHost xmlns:an ...

  10. Mono Touch Table应用

    , UIApplication.SharedApplication.StatusBarFrame.Height                         , UIScreen.MainScree ...