简单说明:ArrayList 在 For 循环中进行删除而产生异常的原因

简介: 经常会有人这么对 list 进行遍历,错而不自知。示例代码如下:public static void main(String[] args) { List<String> list = new ArrayList<>(); list.

经常会有人这么对 list 进行遍历,错而不自知。

示例代码如下:

public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("aaa");
    list.add("bbb");
    list.add("ccc");
    list.add("ddd");

    for (String str : list) {
        if ("aaa".equals(str)) {
            list.remove("aaa");
        }
    }
}

以上代码执行导致的报错信息如下:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at demo.service.impl.test.main(test.java:14)

网上有很多博客对此都做了说明,这篇文章通过比较浅显易懂的方式说明报错产生的原因。

一、list.add

list.add 代码执行时,有一个变量发生改变了,那就是 modCount。在代码中 list.add 共执行4次,所以 modCount 的值为 4。

注:listadd()remove()clear() 都会改变 modCount 值。

二、for (String str : list)

for (String str : list) 调用的是 ArrayList 中内部类 ItrItr 是对 Iterator 的实现。而在 Iterator 开始前,会先执行 int expectedModCount = modCount

此时 expectedModCountmodCount 均为 4

三、list.remove("aaa")

在此处先看一下会报错的原因,以下是源码:

final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

modCountexpectedModCount 不相等了,所以报错。

有人可能会跟我有一样的想法,为什么 list.remove("aaa") 时,不把 expectedModCount = modCount 重新赋值一次。其实是有的,只是调用的方法错了。

例子中 list.remove("aaa") 调用的 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
                fastRemove(index);
                return true;
            }
    }
    return false;
}

而使 modCount 的值改变的是其中的 fastRemove 方法。

fastRemove 源码如下:

private void fastRemove(int index) {
    // 此处 modCount + 1
    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
}

而真正使 expectedModCount = modCount 执行的源码如下:

public void remove() {
    if (lastRet < 0)
        throw new IllegalStateException();
    checkForComodification();

    try {
        AbstractList.this.remove(lastRet);
        if (lastRet < cursor)
            cursor--;
        lastRet = -1;
        expectedModCount = modCount;
    } catch (IndexOutOfBoundsException e) {
        throw new ConcurrentModificationException();
    }
}

此代码在内部类 Itr 中。

这也就是为什么会说,如果 list 在循环中有删除操作,最好用 iterator 迭代的方式去做。

四、总结

简单总结一下

  • list.remove() 没有对 expectedModCount 重新赋值
  • iterator.remove()expectedModCount 重新赋值

建议大家跟踪一下源代码,代码量不多,也很容易理解。

附录:内部类 Itr 源码(不长,分分钟看完)

private class Itr implements Iterator<E> {
    /**
     * Index of element to be returned by subsequent call to next.
     */
    int cursor = 0;

    /**
     * Index of element returned by most recent call to next or
     * previous.  Reset to -1 if this element is deleted by a call
     * to remove.
     */
    int lastRet = -1;

    /**
     * The modCount value that the iterator believes that the backing
     * List should have.  If this expectation is violated, the iterator
     * has detected concurrent modification.
     */
    int expectedModCount = modCount;

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

    public E next() {
        checkForComodification();
        try {
            int i = cursor;
            E next = get(i);
            lastRet = i;
            cursor = i + 1;
            return next;
        } catch (IndexOutOfBoundsException e) {
            checkForComodification();
            throw new NoSuchElementException();
        }
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            AbstractList.this.remove(lastRet);
            if (lastRet < cursor)
                cursor--;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException e) {
            throw new ConcurrentModificationException();
        }
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}
相关文章
|
29天前
使用List中的remove方法遇到数组越界
使用List中的remove方法遇到数组越界
17 2
|
2月前
|
存储 前端开发 索引
Map循环注意事项
Map循环注意事项
12 0
|
9月前
|
存储 前端开发 索引
map循环注意事项
map循环注意事项
78 0
|
10月前
for-each或迭代器中调用List的remove方法会抛出ConcurrentModificationException的原因
for-each循环遍历的实质是迭代器,使用迭代器的remove方法前必须调用一下next()方法,并且调用一次next()方法后是不允许多次调用remove方法的,为什么呢?接下来一起来看吧
55 0
|
Java API
Java的List,如何删除重复的元素,教你三个方法搞定!
Java的List,如何删除重复的元素,教你三个方法搞定!
249 0
|
Java
Java面试题:循环删除 List 中的元素
Java面试题:循环删除 List 中的元素
112 0
有关使用Arrays.asList(array) 转换成List集合之后,对其进行操作抛出UnsupportedOperationException异常的问题
有关使用Arrays.asList(array) 转换成List集合之后,对其进行操作抛出UnsupportedOperationException异常的问题
83 0
|
Java C++
【Java基础】探索List和Map循环遍历删除问题
Java代码写的其实不多,上周写List和Map的遍历,需要删除里面的元素时,直接就抛出异常,因为接触Java时间并不长,这种方式之前也很少使用,所以感觉这里肯定有坑,然后Java对List和Map的遍历方式也是五花八门,今天想花点时间研究了一下。
449 0
【Java基础】探索List和Map循环遍历删除问题
|
Java 索引
Java 循环删除list中指定元素
Java 循环删除list中指定元素
Java 循环删除list中指定元素
|
Java 索引
Java foreach中List移除元素抛出ConcurrentModificationException原因全解析
Java foreach中List移除元素抛出ConcurrentModificationException原因全解析
315 0
Java foreach中List移除元素抛出ConcurrentModificationException原因全解析