先贴ArrayListL里面
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;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
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];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
增强for循环底层就是用的iterator的hasNext()和next()进行判断操作
hasNext方法
public boolean hasNext() { return cursor != size; }
拿cursor和list的size进行比对,如果为true,才进行next方法操作。cursor初始值是0,每进行一次正常的next操作之后,cursor+1
假设一开始list泛型是字符串里面有2个元素“a”,“b”,在增强for循环里面删除a这个元素,
for(String s:list){
if(s.equals("a)){
list.remove(s);
}
}
首先第一次hasNext(),cursor=0,size=2,0!=2返回true进入next()方法,cursor=1,删除list中的"a"元素,list的size变为1
再进行第二次hasNext(),此时cursor=1,size=1,1!=1返回false,循环结束,没有抛ConcurrentModificationException异常。
结论:增强for循环或iterator循环时,用list去删除倒数第二个元素,都不会抛异常,但这种场景下,list中的最后一个元素不会被遍历到