Java集合类中modCount的作用

638 阅读1分钟

结论

防止并发情况下出现数据异常的问题

modCount - 记录当前集合被修改的次数

  1. 添加
  2. 删除

上述两个操作会影响modCount的值

以ArrayList为例, 其Iterator实现如下

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;

    // prevent creating a synthetic constructor
    Itr() {}

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

使用Iterator遍历时会把List的modCount赋值给expectedModCount,在调用Iteratornext()或者remove()方法时会调用checkForComodification()方法检查是否在遍历时有其他访问者对List进行了增删操作,若在这期间有过修改,则会直接抛出异常

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