使用迭代器遍历List的时候修改List报ConcurrentModificationException异常原因分析

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

 1 package com.others;
2
3 import java.util.ArrayList;
4 import java.util.Iterator;
5 import java.util.List;
6 import java.util.concurrent.CopyOnWriteArrayList;
7
8 public class ArrayListTest {
9
10 public static void main(String[] args) {
11 List<String> list = new ArrayList<String>();
12 //CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
13 list.add("a");
14 list.add("b");
15 list.add("c");
16 list.add("d");
17 list.add("e");
18 Iterator iterator = list.iterator();
19 while(iterator.hasNext()){
20 String str = (String) iterator.next();
21 if(str.equals("c")){
22 list.remove(str);
23 }else{
24 System.out.println(str);
25 }
26 }
27 }
28
29 }

  结果为:

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接口):

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

  我们看一下Itr这个类:

 1 private class Itr implements Iterator<E> {
2 int cursor; // index of next element to return
3 int lastRet = -1; // index of last element returned; -1 if no such
4 int expectedModCount = modCount; //刚创建迭代对象的时候List的modCount
5
6 public boolean hasNext() {
7 return cursor != size;
8 }
9
10 @SuppressWarnings("unchecked")
11 public E next() {
12 checkForComodification(); //每调用一次next()函数都会调用checkForComodification方法判断一次
13 int i = cursor;
14 if (i >= size)
15 throw new NoSuchElementException();
16 Object[] elementData = ArrayList.this.elementData;
17 if (i >= elementData.length)
18 throw new ConcurrentModificationException();
19 cursor = i + 1;
20 return (E) elementData[lastRet = i];
21 }
22
23 public void remove() {
24 if (lastRet < 0)
25 throw new IllegalStateException();
26 checkForComodification();
27
28 try {
29 ArrayList.this.remove(lastRet);
30 cursor = lastRet;
31 lastRet = -1;
32 expectedModCount = modCount;
33 } catch (IndexOutOfBoundsException ex) {
34 throw new ConcurrentModificationException();
35 }
36 }
37 //此方法用来判断创建迭代对象的时候List的modCount与现在List的modCount是否一样,不一样的话就报ConcurrentModificationException异常
38 final void checkForComodification() {
39 if (modCount != expectedModCount)
40 throw new ConcurrentModificationException();
41 }
42 }

  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()方法:

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

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

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

我喜欢,驾驭着代码在风驰电掣中创造完美!我喜欢,操纵着代码在随必所欲中体验生活!我喜欢,书写着代码在时代浪潮中完成经典!每一段新的代码在我手中诞生对我来说就象观看刹那花开的感动!
欢迎分享与转载
0
 

修改List报ConcurrentModificationException异常原因分析的更多相关文章

  1. 使用迭代器遍历List的时候修改List报ConcurrentModificationException异常原因分析

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

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

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

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

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

  4. Java ConcurrentModificationException异常原因和解决方法

    Java ConcurrentModificationException异常原因和解决方法 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会抛出java.u ...

  5. Java并发编程:Java ConcurrentModificationException异常原因和解决方法

    Java ConcurrentModificationException异常原因和解决方法 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会抛出java.u ...

  6. 【转】Java ConcurrentModificationException异常原因和解决方法

    原文网址:http://www.cnblogs.com/dolphin0520/p/3933551.html Java ConcurrentModificationException异常原因和解决方法 ...

  7. 9、Java ConcurrentModificationException异常原因和解决方法

    Java ConcurrentModificationException异常原因和解决方法 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会抛出java.u ...

  8. (转)Java ConcurrentModificationException异常原因和解决方法

    转载自:http://www.cnblogs.com/dolphin0520/p/3933551.html 在前面一篇文章中提到,对Vector.ArrayList在迭代的时候如果同时对其进行修改就会 ...

  9. java.util.ConcurrentModificationException异常原因及解决方法

    在java语言中,ArrayList是一个很常用的类,在编程中经常要对ArrayList进行删除操作,在使用remove方法对ArrayList进行删除操作时,报java.util.Concurren ...

随机推荐

  1. TRILL浅析

    1 TRILL概述 TRILL的全称就是Transparent Interconnection of Lots of Links,顾名思义,其本质就是将非常多条链路透明地组织在一起,以致于上层IP应用 ...

  2. swift学习:第一个swift程序

    原文:swift学习:第一个swift程序 最近swift有点火,赶紧跟上学习.于是,个人第一个swift程序诞生了... 新建项目

  3. 分享一个解析XML成为php数组的方法

    原文:分享一个解析XML成为php数组的方法 <?php /* * To change this template, choose Tools | Templates * and open th ...

  4. c# 数据类型转换 as(C# 参考)

    as    运算符类似于强制转换操作.               但是,因此,如果转换是不可能的,as 返回 null 而不引发异常.  请看下面的示例: expression is type ? ...

  5. 详解linux vi命令用法

    vi是所有UNIX系统都会提供的屏幕编辑器,它提供了一个视窗设备,通过它可以编辑文件.当然,对UNIX系统略有所知的人,或多或少都觉得vi超级难用,但vi是最基本的编辑器,所以希望读者能好好把它学起来 ...

  6. MVC验证03-自定义验证规则、禁止输入某些值

    原文:MVC验证03-自定义验证规则.禁止输入某些值 本文继续体验自定义验证规则,需求是禁止输入某些值.本文与前2篇相关,请参考:MVC验证01-基础.远程验证   MVC验证02-自定义验证规则.邮 ...

  7. HDU 4324 Triangle LOVE 拓扑排序

    Problem Description Recently, scientists find that there is love between any of two people. For exam ...

  8. AngularJS学习笔记(一)——一些基本知识

    (一)Hello Angular index.html <!DOCTYPE html> <html ng-app> <head> <title>Test ...

  9. Django小例子 – 模型数据的模板呈现

    学习Django的这几天,学习过程还是很愉快的,django采用的MVC架构,学习曲线十分平缓,在深入学习之前,先简单的整理记录下django从数据库中获取数据并在模板中使用的方法.温故而知新 ^_^ ...

  10. OCP-1Z0-051-题目解析-第4题

    4. Which two statements are true regarding single row functions? (Choose two.) A. They a ccept only ...