/**
* An optimized version of AbstractList.Itr
*/privateclassItrimplementsIterator<E>{int cursor;// index of next element to returnint lastRet =-1;// index of last element returned; -1 if no such//快速失败参数int expectedModCount = modCount;// prevent creating a synthetic constructorItr(){}publicbooleanhasNext(){return cursor != size;}@SuppressWarnings("unchecked")public E next(){//检查快速失败checkForComodification();int i = cursor;if(i >= size)thrownewNoSuchElementException();
Object[] elementData = ArrayList.this.elementData;//外部一定修改集合if(i >= elementData.length)thrownewConcurrentModificationException();
cursor = i +1;return(E) elementData[lastRet = i];}publicvoidremove(){if(lastRet <0)thrownewIllegalStateException();checkForComodification();try{
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet =-1;//在本迭代中移除数据,则更新快速失败参数
expectedModCount = modCount;}catch(IndexOutOfBoundsException ex){thrownewConcurrentModificationException();}}@OverridepublicvoidforEachRemaining(Consumer<?super E> action){
Objects.requireNonNull(action);finalint size = ArrayList.this.size;int i = cursor;if(i < size){final Object[] es = elementData;if(i >= es.length)thrownewConcurrentModificationException();for(; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));// update once at end to reduce heap write traffic
cursor = i;
lastRet = i -1;checkForComodification();}}/*
* 快速失败检查,在本迭代外修改集合,迭代失败
*/finalvoidcheckForComodification(){if(modCount != expectedModCount)thrownewConcurrentModificationException();}}
快速失败在用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了修改(增加、删除、修改),则会抛出 Concurrent Modification Exception --- 并发修改异常。modCount此列表被<i>结构修改</i>的次数。结构性修改是指更改列表大小或以其他方式干扰列表进行进度可能会产生不正确结果的方式。1. 添加数据2. 移除数据3. 容量变化代码/** * An optimized version of Abstract