ArrayList中的modCount与ConcurrentModificationException

在看ArrayList源码时,看到了一个字段modCount。在add、remove、clear等方法中都有modCount++的操作。不明白什么意思。点进去看了看该字段的解释,总算明白了。modCount是在AbstractList抽象类中定义的。该字段的解释如下所示。

    /**
     * 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.
     * 该list结构性改变的次数。结构改变是指list的大小改变了,或者顺序被打乱,从而
     * 导致iterations在执行过程中得到错误的结果。
     *
     * <p>This field is used by the iterator and list iterator implementation
     * returned by the {@code iterator} and {@code listIterator} methods.
     * If the value of this field changes unexpectedly, the iterator (or list
     * iterator) will throw a {@code ConcurrentModificationException} in
     * response to the {@code next}, {@code remove}, {@code previous},
     * {@code set} or {@code add} operations.  This provides
     * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
     * the face of concurrent modification during iteration.
     * 该字段用于iterator和listIterator方法返回的iterator和list iterator实现数据迭代。
     * 如果该字段出现了意外的改变,iterator/list iterator在执行next、remove、previous、
     * set、add等操作时将抛出ConcurrentModificationException。 这样就提供了快速失败行为,
     * 而不会出现在执行迭代过程中的不确定行为。
     *
     * <p><b>Use of this field by subclasses is optional.</b> If a subclass
     * wishes to provide fail-fast iterators (and list iterators), then it
     * merely has to increment this field in its {@code add(int, E)} and
     * {@code remove(int)} methods (and any other methods that it overrides
     * that result in structural modifications to the list).  A single call to
     * {@code add(int, E)} or {@code remove(int)} must add no more than
     * one to this field, or the iterators (and list iterators) will throw
     * bogus {@code ConcurrentModificationExceptions}.  If an implementation
     * does not wish to provide fail-fast iterators, this field may be
     * ignored.
     * 子类是否使用该字段是可选的。 如果子类想要提供快速失败的iterator/list iterator,
     * 只需要在其add、remove或者其他重载的会导致list结构改变的方法中增加该字段的值。
     * 单次都add或者remove的调用对该字段值的增加不能超过1,否则iterator/list iterator
     * 将抛出虚假的ConcurrentModificationExceptions。 如果实现类不想提供快速失败的迭代器,
     * 可以忽略掉该字段。
     */
    protected transient int modCount = 0; 
    //如果不晓得transient干嘛的,请自觉去面壁☺

关于ConcurrentModificationException,请参考: Java遍历时删除List、Set、Map中的元素(源码分析)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值