JAVA循环迭代中删除或添加集合数据报java.util.ConcurrentModificationException错误
1.写出下面的输出结果
public class test{
public static void main(String [] args)
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf(i));
}
for(String s : list){
if(s.equals("3")){
list.remove(s);
}
}
System.out.println(list.size());
}
}
正确的输出:发生了并发的错误
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at test.main(test.java:35)
在这里for(String s : list){}的实质还是Iterator接口。
上面这段代码等价于下面:
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String itString = (String)iterator.next();
if (itString.equals("3")) {
list.remove(itString); --这里会报错
//iterator.remove();---这里不会报错
}
}
所以我们来看看 list.iterator();的源码就知道为什么了
public Iterator<E> iterator() {
return new Itr();
}
/**
* 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;
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();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
从源码上我们可以看出,当我们调用next()方法的时候有一个检查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 remove method that skips bounds checking and does not
* return the value removed.
*/
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的时候modeCount的值发生了变化,这就导致和expectedModCount的值相等了,故报错。
从源码中我们还得知,在clear方法,add方法,addAll方法,removeRange方法时都会导致modeCount的值发生变化。
所以当我们想在循环中对List进行删除时不能用List的remove*方法。但是可以用iterator.remove();从上面的源码中我们可以知道这个方法中进行了
expectedModCount=ModCount对expectedModCount重新赋值。
JAVA循环迭代中删除或添加集合数据报java.util.ConcurrentModificationException错误的更多相关文章
- 遍历List过程中删除操作报java.util.ConcurrentModificationException错误
1:遍历List 同时 remove 元素,出现java.util.ConcurrentModificationException错误 @Test public void test3(){ List& ...
- Java循环遍历中直接修改遍历对象
Java 循环遍历中直接修改遍历对象如下,会报异常: for (ShopBaseInfo sp: sourceList) { if(sp.getId()==5){ sourceList.remove( ...
- Java中删除第一个集合中以某某开头的元素,删除第二个集合中以某某结尾的元素,并合并成一个集合
import java.util.ArrayList; import java.util.List; public class Test { public static void main(Strin ...
- 【java】TreeMap/HashMap的循环迭代中 keySet和entrySet和forEach方式 + map的几种迭代方式
参考链接:https://www.cnblogs.com/crazyacking/p/5573528.html ================================== java紫色代表迭 ...
- java ArrayList迭代过程中删除
第一种迭代删除方式: 第二种迭代删除方式: 第三种迭代删除: 第四种迭代删除: 第五种迭代删除: 第六种: ArrayList中remove()方法的机制,首先看源码: 真正的删除操作在fastRem ...
- cmd中删除、添加、修改注册表命令
转自:http://www.jb51.net/article/30586.htm regedit的运行参数 REGEDIT [/L:system] [/R:user] filename1 REGEDI ...
- js实现在表格中删除和添加一行
<!DOCTYPE html><html> <head> <title> new document </title> <meta ht ...
- For循环List中删除正确的方式
单线程public class Test { public static void main(String[] args) { ArrayList<Integer> list = new ...
- Java 遍历List中删除的解决方法
随机推荐
- linux 标准输出和后台运行
一.后台运行程序 至需要在命令后面加上一个 & 即可 # command & 例如: python test.py & 二.标准输出.标准错误输出 # command > ...
- python之路——迭代器和生成器
阅读目录 楔子 python中的for循环 可迭代协议 迭代器协议 为什么要有for循环 初识生成器 生成器函数 列表推导式和生成器表达式 本章小结 生成器相关的面试题 返回顶部 楔子 假如我现在有一 ...
- 移动端 fixed 固定按钮在屏幕下方,然后按钮被键盘顶上来...顶上来了有没有~
在移动端 H5 页面开发中,我使用了 fixed 固定某个元素在屏幕的最下方, 这时点击输入框,接着非常非常自然地出现了元素被系统键盘顶起来的情况,如下图. 解决方案: 首先,给页面最外层包裹一层 d ...
- 原生js做h5小游戏之打砖块
前言 首先,先说明一下做这个系列的目的:其实主要源于博主希望熟练使用 canvas 的相关 api ,同时对小游戏的实现逻辑比较感兴趣,所以希望通过这一系列的小游戏来提升自身编程能力:关于 es6 语 ...
- ACM 手机短号问题
手机短号 Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Description ...
- cms初步构想
一.cms系统的初步构想 公司正准备使用yii框架重新弄个类cms的系统: 初步的功能: 栏目文章的管理 SEO的优化功能 推荐位管理 一些思路和规则: 数据库表名的定义:通过"大模块名称+ ...
- LINQ(Language Integrated Query)
LINQ http://www.cnblogs.com/lifepoem/archive/2011/12/16/2288017.html LINQ是.NET Framework 3.5的新特性,其全称 ...
- <轉>APUE:mmap函数
起初 看过一遍内存映射I/O,意思大概是懂了,就是直接操作文件再而直接通过缓冲区来操作,减少一些read.write调用所花费的时间.加上文中给出一个copy的例子,意思也好理解的.不过困扰的来了,我 ...
- matlab学习GUI的基本操作
在命令行窗口输入guide 单击确定后出现,可以选择控件来设计,然后可以保存 右击可以查看控件的所有属性 举一个简单的GUI实例---实现数据的传输 添加可编辑文本框 更改字体大小,string默认的 ...
- 对服务器磁盘、CPU、内存使用状态,设置163邮件告警
1,桥接模式可上网,首先你的邮箱已经开通yum -y install mailx dos2unix.x86_64 mailx -V[root@localhost ~]# vim /etc/mail. ...