java-关于List删除元素的出错问题

java-关于List删除元素的出错问题

问题

最近发现直接使用list.remove(item)时报了以下错误:

java.util.ConcurrentModificationException: null

解决方法如下:

Iterator<OrderDetl> iterator = list.iterator();
while(iterator.hasNext()){
  OrderDetl detl = iterator.next();
  for (int i = 0; i < bookIds.size(); i++) {
   if (detl.getBookId().equals(bookIds.get(i))) {
        iterator.remove(); //剔除
        break;
        }
    }
 }
// 以下删除方法会报错
//  for (OrderDetl detl : list) {
//     for (int i = 0; i < bookIds.size(); i++) {
//           if (detl.getBookId().equals(bookIds.get(i))) {
//               list.remove(detl); //剔除
//                   break;
//                }
//          }
//     }

原因:

调用list.remove()方法导致modCount和expectedModCount的值不一致。

源码分析

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 void fastRemove(int index) {
    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
}

  通过remove方法删除元素最终是调用的fastRemove()方法,在fastRemove()方法中,首先对modCount进行加1操作(因为对集合修改了一次),然后接下来就是删除元素的操作,最后将size进行减1操作,并将引用置为null以方便垃圾收集器进行回收工作。

  那么注意此时各个变量的值:对于iterator,其expectedModCount为0,cursor的值为1,lastRet的值为0。

  对于list,其modCount为1,size为0。

  接着看程序代码,执行完删除操作后,继续while循环,调用hasNext方法()判断,由于此时cursor为1,而size为0,那么返回true,所以继续执行while循环,然后继续调用iterator的next()方法:

  注意,此时要注意next()方法中的第一句:checkForComodification()。

  在checkForComodification方法中进行的操作是:

final void checkForComodification() {
    if (modCount != expectedModCount)
    throw new ConcurrentModificationException();
}

  如果modCount不等于expectedModCount,则抛出ConcurrentModificationException异常。

  很显然,此时modCount为1,而expectedModCount为0,因此程序就抛出了ConcurrentModificationException异常。

posted @ 2020-12-28 13:22  DurianTRY  阅读(408)  评论(0编辑  收藏  举报