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发生改变就会报错。