List安全删除元素

bug天天写,今天特别惨。

刚刚上线的功能,还没多久就报bug,不得不回滚,第一次啊,哎,小心脏受不了。虽然我自己脸皮厚,但给团队带来的负面影响和工作效率影响让我很难受。总结总结吧,血淋淋教训一。

问题出在一个ArrayList,我用foreach的循环剔除里面不需要的元素,如下:

for (ThrowBean throwBean : needCheckThrowBeans) {
    if (throwBean.getStatus() == 1 || throwBean.getStatus() == 2) {
        needCheckThrowBeans.remove(throwBean);
    }
}
乍一看,没啥问题,可是问题往往隐藏才不注意的地方。抛去异常: ConcurrentModificationException


As everyone knows,foreach迭代循环,会调用Iterator.next(),可参照:http://blog.csdn.net/a596620989/article/details/6930479

再查看ArryList源码,它继承了AbstractList<E>,其Iterator相关代码如下:


private class Itr implements Iterator<E> {
        /**
         * Index of element to be returned by subsequent call to next.
         */
        int cursor = 0;

        /**
         * Index of element returned by most recent call to next or
         * previous.  Reset to -1 if this element is deleted by a call
         * to remove.
         */
        int lastRet = -1;

        /**
         * The modCount value that the iterator believes that the backing
         * List should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size();
        }

        public E next() {
            checkForComodification();  // 在next方法中调用这个check方法
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount) // 在这里抛出了异常
                throw new ConcurrentModificationException();
        }
    }
在看看ArrayList的remove方法:



public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

    /*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    private void fastRemove(int index) {
        modCount++;       // 修改了modCount值
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
    }
可以看出在fastRemove中修改了modCount值,致使在调用next时,抛出了异常。


找到了原因,就选用普通for循环来解决这个问题,但是,在删除list元素时,整个list元素会挪动,更新下标,所以for循环中必须在删除元素后,对下标进行更新。但是从后往前遍历就会规避这个问题,下面是最终的解决方法,网上有很多种,但是我觉得这种是比较巧妙容易理解的。


for (int i = needCheckThrowBeans.size() - 1; i >= 0; i--) {
    if (needCheckThrowBeans.get(i).getStatus() == 1 || needCheckThrowBeans.get(i).getStatus() == 2) {
        needCheckThrowBeans.remove(i);
    }
}

最后,补上一些比较有启发的原理,搜到的:

Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动的时候就找不到要迭代的对象,所以按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。

所以 Iterator 在工作的时候是不允许被迭代的对象被改变的。但你可以使用 Iterator 本身的方法 remove() 来删除对象, Iterator.remove() 方法会在删除当前迭代对象的同时维护索引的一致性。

这是参考这篇帖子写的,感谢:http://www.blogjava.net/EvanLiu/archive/2008/08/31/224453.html



转载于:https://my.oschina.net/collaroid/blog/139021

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值