容器中的modCount作用

这是用来记录容器的修改次数
在使用迭代器遍历的时候,如果使用ArrayList中的remove(int index) remove(Object o) remove(int fromIndex ,int toIndex) add等方法的时候都会修改modCount,在迭代的时候需要保持单线程的唯一操作,如果期间进行了插入或者删除,就会被迭代器检查获知,从而出现运行时异常
java.util.ConcurrentModificationException异常.

List<Integer> a=new ArrayList<Integer>();
            a.add(1);
        Iterator<Integer> it=a.iterator();
        while(it.hasNext()){
            Integer i=it.next();
            if(i==1){
                a.remove(i);//抛出异常
  迭代器初始化的时候   expectedModCount 和modcount都为0;当执行remove后  modcount为1;不相等报错.

      It.remove();//正常运行.

迭代器调用的remove还是list里面的remove; 所以modcount还是++了但是迭代器的remove多了一句
expectedModCount = modCount; 所以两个最后相等,所以不报错.

      }       

}

迭代器代码

 private class Itr implements Iterator<E> {

        int cursor = 0;
        int lastRet = -1;
        int expectedModCount = modCount;//这个就是为了验证现在遍历的容器是不是没被修改过


public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();//判断expectedModCount = modCount是否相等;

            try {
                AbstractList.this.remove(lastRet);//调用list中的remove方法.
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;//关键的一句
            } catch (IndexOutOfBoundsException e) {
                throw new    ConcurrentModificationException();
            }
        }

详细:http://www.cnblogs.com/dolphin0520/p/3933551.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值