image.png

    原文地址: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循环遍历中删除元素会发现什么呢?

    本着一颗好奇的心,一起来研究研究。

    先说现象:

    1. List<String> list = new ArrayList<String>();
    2. list.add("1");
    3. list.add("2");
    4. for (String temp : list) {
    5. if ("1".equals(temp)) {
    6. list.remove(temp);
    7. }
    8. }
    9. System.out.println(list);

    试一下就知道,这段代码不会报错,会正常输出“[2]”

    而当我们删除“2”时,却会出现异常 ;

    1. Exception in thread "main" java.util.ConcurrentModificationException
    2. at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    3. at java.util.ArrayList$Itr.next(ArrayList.java:851)
    4. at com.fansion.MethodTest.main(MethodTest.java:49)

    然后我们把数据弄多一点:

    1. List<String> list = new ArrayList<String>();
    2. list.add("1");
    3. list.add("2");
    4. list.add("3");
    5. list.add("4");
    6. list.add("5");
    7. for (String temp : list) {
    8. if ("4".equals(temp)) {
    9. list.remove(temp);
    10. }
    11. }
    12. System.out.println(list);

    发现一个很神奇的现象,那就是只有在删除倒数第二个元素时不会报错,其他情况下都会报错。

    是不是很诡异!

    更诡异是,若不使用foreach快速遍历,直接使用for(int i;i<list.size();i++)却没有任何问题,可以随便的删。

    1. List<String> list = new ArrayList<String>();
    2. list.add("1");
    3. list.add("2");
    4. list.add("3");
    5. list.add("4");
    6. list.add("5");
    7. for (int i = 0; i < list.size(); i++) {
    8. String temp = list.get(i);
    9. if ("3".equals(temp)) {
    10. list.remove(temp);
    11. }
    12. }
    13. System.out.println(list);

    到底是什么原因呢?

    由于两种遍历的方式不一样,结果就不一样,可以推测出问题可能出现在For-Each遍历上。

    为了弄清楚这个问题,我们一步步的分析Java中ArrayList在遍历和删除的源代码。

    1)直接进入ArrayList的源代码可以发现,在1.5的版本后,ArrayList中创建了一个内部迭代器Itr,并实现了Iterator接口,而For-Each遍历正是基于这个迭代器的hasNext()和next()方法来实现的;

    先看一下这个内部迭代器:

    1. /**
    2. * An optimized version of AbstractList.Itr
    3. */
    4. private class Itr implements Iterator<E> {
    5. int cursor; // index of next element to return
    6. int lastRet = -1; // index of last element returned; -1 if no such
    7. int expectedModCount = modCount;
    8. public boolean hasNext() {
    9. return cursor != size;
    10. }
    11. @SuppressWarnings("unchecked")
    12. public E next() {
    13. checkForComodification();
    14. int i = cursor;
    15. if (i >= size)
    16. throw new NoSuchElementException();
    17. Object[] elementData = ArrayList.this.elementData;
    18. if (i >= elementData.length)
    19. throw new ConcurrentModificationException();
    20. cursor = i + 1;
    21. return (E) elementData[lastRet = i];
    22. }
    23. public void remove() {
    24. if (lastRet < 0)
    25. throw new IllegalStateException();
    26. checkForComodification();
    27. try {
    28. ArrayList.this.remove(lastRet);
    29. cursor = lastRet;
    30. lastRet = -1;
    31. expectedModCount = modCount;
    32. } catch (IndexOutOfBoundsException ex) {
    33. throw new ConcurrentModificationException();
    34. }
    35. }
    36. @Override
    37. @SuppressWarnings("unchecked")
    38. public void forEachRemaining(Consumer<? super E> consumer) {
    39. Objects.requireNonNull(consumer);
    40. final int size = ArrayList.this.size;
    41. int i = cursor;
    42. if (i >= size) {
    43. return;
    44. }
    45. final Object[] elementData = ArrayList.this.elementData;
    46. if (i >= elementData.length) {
    47. throw new ConcurrentModificationException();
    48. }
    49. while (i != size && modCount == expectedModCount) {
    50. consumer.accept((E) elementData[i++]);
    51. }
    52. // update once at end of iteration to reduce heap write traffic
    53. cursor = i;
    54. lastRet = i - 1;
    55. checkForComodification();
    56. }
    57. final void checkForComodification() {
    58. if (modCount != expectedModCount)
    59. throw new ConcurrentModificationException();
    60. }
    61. }

    这里有两个变量需要注意:

    一个是modCount:这个外部的变量,也就是ArrayList下的变量:

    1. /**
    2. * The number of times this list has been <i>structurally modified</i>.
    3. * Structural modifications are those that change the size of the
    4. * list, or otherwise perturb it in such a fashion that iterations in
    5. * progress may yield incorrect results.
    6. *
    7. ….
    8. */
    9. protected transient int modCount = 0;

    只贴前面一部分注释,注释说这个变量来记录ArrayList集合的修改次数,也说明了可能会和迭代器内部的期望值不一致;

    另外一个是Itr的变量expectedModCount:
    能过上面的代码可以看到在Itr创建时默认定义了 int expectedModCount = modCount ;

    我们先只看remove的操作;

    通过在if条件成立时remove(“3”)操作的断点,我们进入到ArrayList下的remove方法,注意这里并没有进入内部迭代器Itr的remove()方法【这里是产生异常的关键点】

    1. public boolean remove(Object o) {
    2. if (o == null) {
    3. for (int index = 0; index < size; index++)
    4. if (elementData[index] == null) {
    5. fastRemove(index);
    6. return true;
    7. }
    8. } else {
    9. for (int index = 0; index < size; index++)
    10. if (o.equals(elementData[index])) {
    11. fastRemove(index);
    12. return true;
    13. }
    14. }
    15. return false;
    16. }

    很显然,这里应该正常的走到了fastRemove()方法中:

    1. /*
    2. * Private remove method that skips bounds checking and does not
    3. * return the value removed.
    4. */
    5. private void fastRemove(int index) {
    6. modCount++;
    7. int numMoved = size - index - 1;
    8. if (numMoved > 0)
    9. System.arraycopy(elementData, index+1, elementData, index,
    10. numMoved);
    11. elementData[--size] = null; // clear to let GC do its work
    12. }

    这里可以看到在fastRemove()方法中通过modCount++ 自增了一次,而此时并没有改变内部迭代器Itr中的 expectedModCount 的值;

    我们再往下走,此会再迭代到下一个元素;
    先会通过hasNext(){return cursor != size;}来判断是否还有元素,很显然,若删除前面的元素,此处一定会为true(注意:若之前删除的是倒数第二个元素,此处的cursor就是最后一个索引值size()-1,而由于已成功删除一个元素,此处的siz也是原size()-1,两者相等,此处会返回false)

    而在调用next()方面来获取下一个元素时,可以看到在next()方法中先调用了 checkForComodification()方法:

    1. final void checkForComodification() {
    2. if (modCount != expectedModCount)
    3. throw new ConcurrentModificationException();
    4. }

    很显然,此处的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(),通过源码可以看到,该方法也就是直接把内部的迭代器返回出来

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

    而该迭代器正是在For-Each快速遍历中使用的迭代器Itr。