今天写一个商品购物车信息管理的小项目,在删除信息时出现了ConcurrentModificationException异常,图如下:
出现异常的方法如下:
通过查阅资料发现,ArrayList在迭代的时候如果同时对其进行修改就会抛出java.util.ConcurrentModificationException异常;
下面是ArrayList类中出错信息对应的类
`
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
通过源码发现在ArrayList的源码中的iterator()这个方法是实现的接口中的方法得来的,接着看源码,调可以发现,出错的关键是用list.remove()方法导致modCount和expectedModCount的值不一致,所以报错。
通过查看源码我们可以发现,当前方法提供了一个remove()方法,所以我们可以直接使用该方法,不同的是需要多一步迭代器的声明,修改后的代码如下:
public void delectShopCarByName(String name){
//System.out.println("进入删除方法");
Iterator iterator = shopCarlist.iterator();
// int i =1;
while(iterator.hasNext()) {
// System.out.println("进入删除方法的for循环"+i++);
ShopCar shopCar = (ShopCar) iterator.next();
if(shopCar.getItems().getName().equals(name)){
iterator.remove();
}
}
}
运行发现,问题解决。
资料查看网址为
https://www.cnblogs.com/zhuyeshen/p/10956822.html