
原文地址:https://zhuanlan.zhihu.com/p/25744271
作者:南山伐木
小结:
1)在使用For-Each快速遍历时,ArrayList内部创建了一个内部迭代器iterator,使用的是hasNext和next()方法来判断和取下一个元素。
2)ArrayList里还保存了一个变量modCount,用来记录List修改的次数,而iterator保存了一个expectedModCount来表示期望的修改次数,在每个操作前都会判断两者值是否一样,不一样则会抛出异常;
3)在foreach循环中调用remove()方法后,会走到fastRemove()方法,该方法不是iterator中的方法,而是ArrayList中的方法,在该方法中modCount++; 而iterator中的expectedModCount却并没有改变;
4)再次遍历时,会先调用内部类iteator中的hasNext(),再调用next(),在调用next()方法时,会对modCount和expectedModCount进行比较,此时两者不一致,就抛出了ConcurrentModificationException异常。
大家都知道,不能在ArrayList的For-Each循环中删除元素。在Java的入门教程中都会写上这条。
可是为什么不能呢?若非要在for循环遍历中删除元素会发现什么呢?
本着一颗好奇的心,一起来研究研究。
先说现象:
List<String> list = new ArrayList<String>();list.add("1");list.add("2");for (String temp : list) {if ("1".equals(temp)) {list.remove(temp);}}System.out.println(list);
试一下就知道,这段代码不会报错,会正常输出“[2]”
而当我们删除“2”时,却会出现异常 ;
Exception in thread "main" java.util.ConcurrentModificationExceptionat java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)at java.util.ArrayList$Itr.next(ArrayList.java:851)at com.fansion.MethodTest.main(MethodTest.java:49)
然后我们把数据弄多一点:
List<String> list = new ArrayList<String>();list.add("1");list.add("2");list.add("3");list.add("4");list.add("5");for (String temp : list) {if ("4".equals(temp)) {list.remove(temp);}}System.out.println(list);
发现一个很神奇的现象,那就是只有在删除倒数第二个元素时不会报错,其他情况下都会报错。
是不是很诡异!
更诡异是,若不使用foreach快速遍历,直接使用for(int i;i<list.size();i++)却没有任何问题,可以随便的删。
List<String> list = new ArrayList<String>();list.add("1");list.add("2");list.add("3");list.add("4");list.add("5");for (int i = 0; i < list.size(); i++) {String temp = list.get(i);if ("3".equals(temp)) {list.remove(temp);}}System.out.println(list);
到底是什么原因呢?
由于两种遍历的方式不一样,结果就不一样,可以推测出问题可能出现在For-Each遍历上。
为了弄清楚这个问题,我们一步步的分析Java中ArrayList在遍历和删除的源代码。
1)直接进入ArrayList的源代码可以发现,在1.5的版本后,ArrayList中创建了一个内部迭代器Itr,并实现了Iterator接口,而For-Each遍历正是基于这个迭代器的hasNext()和next()方法来实现的;
先看一下这个内部迭代器:
/*** An optimized version of AbstractList.Itr*/private class Itr implements Iterator<E> {int cursor; // index of next element to returnint lastRet = -1; // index of last element returned; -1 if no suchint expectedModCount = modCount;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 trafficcursor = i;lastRet = i - 1;checkForComodification();}final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}}
这里有两个变量需要注意:
一个是modCount:这个外部的变量,也就是ArrayList下的变量:
/*** The number of times this list has been <i>structurally modified</i>.* Structural modifications are those that change the size of the* list, or otherwise perturb it in such a fashion that iterations in* progress may yield incorrect results.*….*/protected transient int modCount = 0;
只贴前面一部分注释,注释说这个变量来记录ArrayList集合的修改次数,也说明了可能会和迭代器内部的期望值不一致;
另外一个是Itr的变量expectedModCount:
能过上面的代码可以看到在Itr创建时默认定义了 int expectedModCount = modCount ;
我们先只看remove的操作;
通过在if条件成立时remove(“3”)操作的断点,我们进入到ArrayList下的remove方法,注意这里并没有进入内部迭代器Itr的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;}
很显然,这里应该正常的走到了fastRemove()方法中:
/** 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}
这里可以看到在fastRemove()方法中通过modCount++ 自增了一次,而此时并没有改变内部迭代器Itr中的 expectedModCount 的值;
我们再往下走,此会再迭代到下一个元素;
先会通过hasNext(){return cursor != size;}来判断是否还有元素,很显然,若删除前面的元素,此处一定会为true(注意:若之前删除的是倒数第二个元素,此处的cursor就是最后一个索引值size()-1,而由于已成功删除一个元素,此处的siz也是原size()-1,两者相等,此处会返回false)
而在调用next()方面来获取下一个元素时,可以看到在next()方法中先调用了 checkForComodification()方法:
final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}
很显然,此处的modCount已经比expectedModCount大1了,肯定不一样,if条件成立,抛出一个ConcurrentModificationException异常。
致此,我们大概理清了为什么在foreach快速遍历中删除元素会崩溃的原因。
总结一下:
1)在使用For-Each快速遍历时,ArrayList内部创建了一个内部迭代器iterator,使用的是hasNext和next()方法来判断和取下一个元素。
2)ArrayList里还保存了一个变量modCount,用来记录List修改的次数,而iterator保存了一个expectedModCount来表示期望的修改次数,在每个操作前都会判断两者值是否一样,不一样则会抛出异常;
3)在foreach循环中调用remove()方法后,会走到fastRemove()方法,该方法不是iterator中的方法,而是ArrayList中的方法,在该方法中modCount++; 而iterator中的expectedModCount却并没有改变;
4)再次遍历时,会先调用内部类iteator中的hasNext(),再调用next(),在调用next()方法时,会对modCount和expectedModCount进行比较,此时两者不一致,就抛出了ConcurrentModificationException异常。
而为什么只有在删除倒数第二个元素时程序没有报错呢?
因为在删除倒数第二个位置的元素后,开始遍历最后一个元素时,先会走到内部类iterator的hasNext()方法时,里面返回的是 return cursor != size; 此时cursor是原size()-1,而由于已经删除了一个元素,该方法内的size也是原size()-1,故 return cursor != size;会返回false,直接退出for循环,程序便不会报错。
最后,通过源代码的判断,要在循环中删除元素,最好的方式还是直接拿到ArrayList对象下的迭代器 list.iterator(),通过源码可以看到,该方法也就是直接把内部的迭代器返回出来
public Iterator<E> iterator() {return new Itr();}
而该迭代器正是在For-Each快速遍历中使用的迭代器Itr。
