美文网首页Android
抛ConcurrentModificationException

抛ConcurrentModificationException

作者: 铜角大王 | 来源:发表于2017-08-10 15:51 被阅读0次

    final void checkForComodification() {

    if (modCount != expectedModCount)

    throw new ConcurrentModificationException();

    }

    即当modCount != expectedModCount时,执行next()就会抛出ConcurrentModificationException

    而什么时候会造成modCount != expectedModCount呢?

    ArrayList.add()方法,每执行一次都会modCount++(当然删除就是modCount--),但不改变expectedModCount的值。expectedModCount的值是在构建迭代的时候初始为expectedModCount=modCount的。

    这就是楼主说的在构建迭代器之后,再使用ArrayList.add()方法就造成了modCount != expectedModCount

    所以构建迭代器后,用迭代器来add和remove就没有问题。因为它会在改变modCount的值之后,又把值赋给了expectedModCount,从而保证modCount=expectedModCount

    相关文章

      网友评论

        本文标题:抛ConcurrentModificationException

        本文链接:https://www.haomeiwen.com/subject/lvvhrxtx.html