这是用来记录容器的修改次数
在使用迭代器遍历的时候,如果使用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();
}
}