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中删除的解决方法
随机推荐
- JVM —— Java 对象占用空间大小计算
零. 为什么要知道 Java 对象占用空间大小 缓存的实现: 在设计 JVM 内缓存时(不是借助 Memcached. Redis 等), 须要知道缓存的对象是否会超过 JVM 最大堆限制, 假设会超 ...
- 【HDOJ 1009】 CRB and String
[HDOJ 1009] CRB and String 每组两个串s t 仅仅由小写字母组成 问从s能不能变成t 改变的操作为选一个字符 在后面加上一个与所选字符不同的字符 这样的操作能够做无数次 问能 ...
- UVA 1201 - Taxi Cab Scheme(二分图匹配+最小路径覆盖)
UVA 1201 - Taxi Cab Scheme 题目链接 题意:给定一些乘客.每一个乘客须要一个出租车,有一个起始时刻,起点,终点,行走路程为曼哈顿距离,每辆出租车必须在乘客一分钟之前到达.问最 ...
- 三星抛出万亿投资计划 布局四大科技创新领域(5G、人工智能、汽车半导体、生物技术四大新兴产业)
三星近日抛出震惊世人的投资计划,未来三年将在全球范围新增投资180万亿韩元(约1万亿元人民币).新增员工4万名.这是韩国单一企业集团大规模的投资计划. 笔者获悉,三星万亿投资计划主要分两大部分,一是在 ...
- 【LeetCode OJ 268】Missing Number
题目链接:https://leetcode.com/problems/missing-number/ 题目:Given an array containing n distinct numbers t ...
- 每天一个linux命令(01):ifconfig命令
许多windows非常熟悉ipconfig命令行工具,它被用来获取网络接口配置信息并对此进行修改.Linux系统拥有一个类似的工具,也就是ifconfig(interfaces config).通常需 ...
- rk3288的pcba模块编译调试笔记【学习笔记】
平台信息:内核:linux3.0.68 系统:android/android6.0平台:rk3288 作者:庄泽彬(欢迎转载,请注明作者) 邮箱:2760715357@qq.com 摘要:最近在负责r ...
- dns tunnel 使用 nishang 下载TXT里的cmd(TXT里)实现CC command+ ceye实现数据外发
摘自:https://hk.saowen.com/a/a06909f1c57cb8452db969b3deede4151de42a7d69f4bb52c5bf027033fb91bd Powershe ...
- HTML5动态时钟
实现效果 源码可以去github下载 地址:https://github.com/feifeiliu/jsBlock 参考:慕课网动态时钟
- AUTOCAD2013 以上利用ACCORECONSOLE+ SCR后台批量清理图纸
无意中浏览到南胜大神的博客,https://www.cnblogs.com/NanShengBlogs/p/10957489.html 受此启发,特意改装此方法用于批量清理图纸,效果极佳. 详细介绍详 ...