Java ArrayList的Iterator源码解析

Iterator是一个非常重要的遍历List的工具,再利用迭代器进行增删改时,往往会产生意想不到的bug,因此我们从源码来理解一下ArrayList的Iterator实现。

rep

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;

cursor记录着下一个需要返回的编号,lastRet记录着上一次返回的元素编号。

这里的modCount是从AbstractList继承来的一个属性,我们每次对ArrayList进行增删改的时候,modCount都会发生改变。可以看出,在Iterator被构造的时候,它就记录了当前的 modCount 值。

checkForComodification()

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

我们直接先来看涉及到modCount的部分。这个函数会判断modCount是否发生改变,如果发生改变就会抛出异常。

next()

public E next() {
    checkForComodification();
    int i = cursor;
    if (i >= size)
        throw new NoSuchElementException();
    Object[] elementData = ArrayList.this.elementData;
    if (i >= elementData.length)
        throw new ConcurrentModificationException();
    cursor = i + 1;
    return (E) elementData[lastRet = i];
}

next()函数就调用了上面的checkForComodification(),这也是我们使用迭代器的同时进行增删改,会抛出异常的原因。

hasNext()

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

size是ArrayList的一个rep,它记录着当前ArrayList的元素个数,因此可以利用size进行判断。

remove()

public void remove() {
    if (lastRet < 0)
        throw new IllegalStateException();
     checkForComodification();

    try {
        ArrayList.this.remove(lastRet);
        cursor = lastRet;
        lastRet = -1;
        expectedModCount = modCount;//此处修改了modCount值
    } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
    }
}

虽然我们不能直接调用list的remove方法进行删除,但是我们可以利用Iterator提供的删除方法进行操作。

经验

我们可以看出,凡是利用Iterator的地方,我们都不能对ArrayList进行任何修改操作,因此我们可以看出:

  • 只能利用Iterator提供的remove进行删除操作
  • 面对多线程还需要删除的时候,必须把整个迭代循环加锁,否则多个迭代器同时删除,互相的modCount发生改变就会报错。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值