微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

当我们删除-1并清空ArrayList时,它会抛出ConcurrentModificationException,当我们从同一个空ArrayList中删除0时,它会抛出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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐