ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(1);
//list.add(3);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
Integer integer = iterator.next();
// 两个元素,删除第一个不会报ConcurrentModifiedException
// 因为在判断hasNext() 的时候游标位置等于数组长度,
// 所以不会执行next()去获取下一个元素,也就不会抛出异常
if(integer == 2) {
list.remove(integer);
}
}
ArrayList内部类Itr的hasNext()方法:
public boolean hasNext() {
// 因为判断使用的不等于,所以两个元素时
// 删除第二个元素后cursor=2,size=1,方法返回true
// 遍历会继续获取next(),并抛出异常
return cursor != size;
}
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];
}
final void checkForComodification() {
// 比较修改数与预期修改数的值,不一致则抛出异常
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}