java list<> get 出错_java-关于List删除元素的出错问题

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

问题

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

java.util.ConcurrentModificationException: null

解决方法如下:

Iterator 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异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值