ConcurrentModificationException,iterator迭代问题[源码分析]

单线程的Iterator迭代过程中删除集合元素

public class TestIterator {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        list.add("6");

        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            String next = it.next();
            if("3".equals(next)) {
                list.remove(3);
            }
            System.out.println(next);
        }


    }
}

以上代码会出现如下异常

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 caoyan.test.TestIterator.main(TestIterator.java:22)

从后往前看:
TestIterator第22行代码:

String next = it.next();

我们在执行代码22行时调用了it.next();这个it是ArrayList调用iterator()返回的对象;这个对象的next()方法如下图:

  public E next() {
            checkForComodification();
            ...

next()方法首先它会调用checkForComodification()这个方法,这个方法很简单,就是比较expectedModCount , modCount 这两个值是不是相等;不相等就抛出异常;如下图:

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

这两个值为什么会不相等,它们各自代表什么含义呢,我们看ArrayList的iterator()方法:

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

    /**
     * An optimized version of AbstractList.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;

Arraylist的iterator()方法,直接创建了一个私有的内部类Itr的对象;expectedModCount 就是定义在这个Itr中的成员变量,而且,在初始化的时候,将modCount赋值给expectedModCount,说明在刚生成Iterator的时候这两个值是相等的.modCount是定义在哪里呢,看下面源码

public class ArrayList<E> extends AbstractList<E>
...
protected transient int modCount = 0;

modCount是AbstractList的成员变量,ArrayList继承下来了.所以modCount代表ArrayList的实际长度.
当我们在iterator的迭代过程中改变了ArrayList的长度,就导致modCount变了,而expectedModCount 没有变,导致不相等报错

可是为什么用iterator的remove方法就不报错呢,我们看Remove方法():

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();
    }
}

可以看到,ArrayList在删除元素后,expectedModCount = modCount;重新赋值,让这两个值相等了.所以,remove方法不会抛出这个异常

评论

暂无评论