集合并发修改异常-foreach的时候不可修改值
Exception in thread "main" java.util.ConcurrentModificationException 并发修改异常引发的思考!
1 foreach循环删除元素
①list遍历删除元素时会报错,比如下面删除字符串"aa",也有遍历不报错的例子,看下面的例子
public class TestMain {
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<String>();
array.add("cc");
array.add("aa");
array.add("bb");
array.add("aa");
for (String str : array) {
if("aa".equals(str)){
array.remove(str);
}
}
System.out.println(array.size());
}
}
console: java.util.ConcurrentModificationException
②下面删除字符串"aa"不会报错
public class TestMain {
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<String>();
array.add("cc");
array.add("aa");
array.add("bb");
for (String str : array) {
if("aa".equals(str)){
array.remove(str);
}
}
System.out.println(array.size());
}
}
console : 2
提出问题:为什么上面都是遍历删除,第二个确没有报错呢?
结论:其实原因很简单,因为第二个例子没有走iterator的next方法,删除了字符串"aa"之后,执行hasNext方法返回false直接退出遍历了,hasNext中就是判断cursor != size;此时的cursor是2,而size正好也是2,所以退出了遍历。
而第一个例子删除字符串"aa"之后,cursor=2,size=3,所以hasNext方法返回的true,会执行next方法。
注:只要遍历中remove了,expectedModCount和modCount就不相等了。
注2:cursor 就类似游标,这里表示第几次,size就是元素个数
同理:iterator的形式遍历同foreach。
2 上面都是通过foreach的方式进行的,如果用普通for循环会怎么样
public class TestMain {
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<String>();
array.add("cc");
array.add("aa");
array.add("bb");
array.add("aa");
for(int i = 0;i < array.size();i++){
if("aa".equals(array.get(i))){
array.remove(i);
}
}
System.out.println(array.size());
}
}
console: 2
结论: 普通for循环可以正常删除,他是根据索引进行删除的,所以没有影响。
根据报错信息可以看到是进入checkForComodification()方法的时候报错了,也就是说modCount != expectedModCount。具体的原因,是在于foreach方式遍历元素的时候,是生成iterator,然后使用iterator遍历。在生成iterator的时候,
会保存一个expectedModCount参数,这个是生成iterator的时候List中修改元素的次数。如果你在遍历过程中删除元素,List中modCount就会变化,如果这个modCount和exceptedModCount不一致,就会抛出异常,这个是为了安全的考虑。
看看list的remove源码:
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; // clear to let GC do its work
}
remove操作导致modCount++
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;
public boolean hasNext() {
return cursor != size;
}
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
总结: 1 foreach遍历,iterator遍历都不能在遍历的过程中使用list.remove或list.add操作,会报并发修改异常。
2 iterator遍历过程中如果需要删除可以使用iterator提供的remove()方法。
3 遍历根据元素索引删除是可行的。
以上属于个人心得,不对之处还望大佬指出,如果对你有帮助会更加激励我。
集合并发修改异常-foreach的时候不可修改值的更多相关文章
- ConcurrentModificationException 集合并发修改异常 解决
import java.util.ArrayList; import java.util.List; import java.util.ListIterator; /** * 问题? * 有一个集合, ...
- 集合框架之——迭代器并发修改异常ConcurrentModificationException
问题: 我有一个集合,如下,请问,我想判断里面有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现. 使用普通迭代器出现的异常: ...
- java 15 - 8 集合框架(并发修改异常的产生原因以及解决方案)
问题? 我有一个集合,如下,请问,我想判断里面有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现. 面试题: Concu ...
- Java基础知识强化之集合框架笔记19:List集合迭代器使用之 并发修改异常的产生原因 以及 解决方案
1. 我有一个集合,如下,请问,我想判断里面有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现. ConcurrentModi ...
- ArrayList在foreach删除倒数第二个元素不抛并发修改异常的问题
平时我们使用ArrayList比较多,但是我们是否知道ArrayList在进行foreach的时候不能直接通过list的add或者move方法进行删除呢, 原因就是在我们进行foreach遍历的时候, ...
- List集合遍历时修改元素出现并发修改异常总结
什么是并发修改异常: 当我们在遍历实现了collection接口与iterator接口的集合时(List.Set.Map), 我们可以通过遍历索引也可以通过迭代器进行遍历.在我们使用迭代器进行遍历集合 ...
- 大杂烩 -- Iterator 并发修改异常ConcurrentModificationException
基础大杂烩 -- 目录 大杂烩 -- Java中Iterator的fast-fail分析 大杂烩 -- Iterator 和 Iterable 区别和联系 问题: 在集合中,判断里面有没有" ...
- 日历类和日期类转换 并发修改异常 泛型的好处 *各种排序 成员和局部变量 接口和抽象类 多态 new对象内存中的变化
day07 ==和equals的区别? ==用于比较两个数值 或者地址值是否相同. equals 用于比较两个对象的内容是否相同 String,StringBuffer.StringBuilde ...
- ConcurrentModificationException(并发修改异常)的解决
[异常解释] ConcurrentModificationException:当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常.[产生的原因] 迭代器是依赖于集合而存在的,在判断成功后,集合 ...
随机推荐
- 海量日志采集系统flume架构与原理
1.Flume概念 flume是分布式日志收集系统,将各个服务器的数据收集起来并发送到指定地方. Flume是Cloudera提供的一个高可用.高可靠.分布式的海量日志采集.聚合和传输的系统.Flum ...
- 基于apache httpclient 调用Face++ API
简要: 本文简要介绍使用Apache HttpClient工具调用旷世科技的Face API. 前期准备: 依赖包maven地址: <!-- https://mvnrepository.com/ ...
- webpack加载多级依赖时css、html文件不能正确resolve的问题
在使用webpack+avalon以及avalon的mmRouter做SPA的时候,碰到一个困扰数周的问题:webpack加载多级依赖时出现了css文件和模板(html)文件不能正确resolve.原 ...
- iOS屏幕适配(尺寸适配)
屏幕尺寸适配:一 在.pch中加入以下代码,在定义每个尺寸值的时候都调用下边的宏 //以iphone7为例 定义 view相关的宽高宏#define IPHONEHIGHT(b) [UIScreen ...
- spring boot入门 -- 介绍和第一个例子
"越来越多的企业选择使用spring boot 开发系统,spring boot牛在什么地方?难不难学?心动不如行动,让我们一起开始学习吧!" 使用Spring boot ,可以轻 ...
- 1-MySQL数据库(android连接MySQL数据库)
很好的链接 http://www.cnblogs.com/best/p/6517755.html 一个小时学会MySQL数据库 http://www.cnblogs.com/klguang/p/47 ...
- Who's in the Middle
FJ is surveying his herd to find the most average cow. He wants to know how much milk this 'median' ...
- 关于VS2017安装的一点扩充说明(15.5)
其实逆天不推荐自己慢慢离线,找个离线包更新下再打包更快 Key:http://www.cnblogs.com/dunitian/p/4667038.html VS完整卸载工具:https://gith ...
- Apache Avro# 1.8.2 Specification (Avro 1.8.2规范)二
h5 { text-indent: 0.71cm; margin-top: 0.49cm; margin-bottom: 0.51cm; direction: ltr; color: #000000; ...
- 百度图表插件echart简单应用,简单配置一些要显示的样式及种类
从echart官网下载js,然后引入jq即可运行.足够简单应用了 关键词:echart控制:图标标题.数据标题.折线图.柱状图切换按钮.恢复刷新图表按钮.保存为图片按钮.坐标系控制.坐标数据.坐标倾斜 ...