当我们从 -1
中删除并清空 ArrayList
时,它会抛出 ConcurrentModificationException
并且当我们从中删除 0
时空 ArrayList
它抛出 NoSuchElementException
。
请在下面找到代码:
public class Test {
public static void main(String[] argv) {
ArrayList<Integer> list = new ArrayList<Integer>();
Iterator<Integer> it = list.iterator();
try {
list.remove(-1);
} catch (IndexOutOfBoundsException e) {
}
try {
it.next();// Throwing ConcurrentModificationException
} catch (ConcurrentModificationException e) {
System.err.println("ConcurrentModificationException 1");
} catch (NoSuchElementException e) {
System.err.println("NoSuchElementException 1 ");
}
list = new ArrayList<Integer>();
it = list.iterator();
try {
list.remove(0);
} catch (IndexOutOfBoundsException e) {
}
try {
it.next();// Throwing NoSuchElementException
} catch (NoSuchElementException e) {
System.err.println("NoSuchElementException 2");
} catch (ConcurrentModificationException e) {
System.err.println("ConcurrentModificationException 2 ");
}
}
}
根据我的理解,NoSuchElementException
很好,但为什么会抛出 ConcurrentModificationException
?
最佳答案
如果检查 ArrayList 的代码。首先执行范围检查,然后添加修改计数。
rangeCheck(index);
modCount++;
在范围检查方法中,范围检查仅针对正数。
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
因此 remove(0)
不会添加 mod 计数,但 remove(-1)
会添加。 modCount 导致迭代器抛出 ConcurrentModificationException。
关于java - ArrayList remove() 的特殊行为 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46441715/