java - ArrayList remove() 的特殊行为 - 为什么?

标签 java arraylist

当我们从 -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/

相关文章:

java - 从 fxml 加载器访问 fxml Controller 的方法

java - 执行 Java 字节码检测的最有前途的方法是什么?

java - java读取文本文件并将数字存储在不同的数组中

java - 如何将计数索引的值分配给ArrayList?不是计数索引的对象

java - 为什么需要 main 方法才能在类中使用 arraylist 方法?

java - 从另一个 Activity 的返回堆栈中删除一个 Activity ?

Java - 创建一个具有指定长度并填充特定字符的新字符串实例。最佳解决方案?

java - 今天早些时候在考试中遇到问题 - ArrayList 方法

java - 为什么ArrayList的默认容量是10?

java - ArrayList of Integers 的 ArrayList 不应接受重复项