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();
}
本文深入探讨了在Java中使用ArrayList的迭代器进行元素删除时的机制,特别关注了在迭代过程中删除元素如何避免ConcurrentModificationException异常。通过具体代码示例,解析了ArrayList内部类Itr的hasNext()和next()方法的工作原理,以及如何正确地在遍历过程中安全地删除元素。
1582

被折叠的 条评论
为什么被折叠?



