Java ConcurrentModificationException异常原因和单线程下的解决方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java ConcurrentModificationException异常原因和单线程下的解决方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2576字,纯文字阅读大概需要4分钟。
内容图文
今天写一个商品购物车信息管理的小项目,在删除信息时出现了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
内容总结
以上是互联网集市为您收集整理的Java ConcurrentModificationException异常原因和单线程下的解决方法全部内容,希望文章能够帮你解决Java ConcurrentModificationException异常原因和单线程下的解决方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。