Exception in thread "main" java.util.ConcurrentModificationException解决方案
我想判断一个集合里面有没有"world"这个元素,如果有,我就添加一个"javaee"元素,
当时的做法是:
public class ListIteratorDemo1 { public static void main(String[] args) {
// 创建List集合对象
List list = new ArrayList();
// 添加元素
list.add("hello");
list.add("world");
list.add("java"); // 迭代器遍历
Iterator it = list.iterator();
while (it.hasNext()) {
String s = (String) it.next();
if ("world".equals(s)) {
list.add("javaee");
}
}
System.out.println("list:" + list);
}
}
但是报了错误Exception in thread "main" java.util.ConcurrentModificationException错误
查阅API知道:
ConcurrentModificationException:当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。
产生此种的原因是:
迭代器是依赖于集合而存在的,在判断成功后,集合的中新添加了元素,而迭代器却不知道,所以就报错了,这个错叫并发修改异常。
其实这个问题简单的描述是:迭代器遍历元素的时候,通过集合是不能修改元素的。
如何解决呢?
A:迭代器迭代元素,迭代器修改元素
元素是跟在刚才迭代的元素后面的。
B:集合遍历元素,集合修改元素(普通for)
元素在最后添加的。
A的解决方案:
public class ListIteratorDemo1 { public static void main(String[] args) {
// 创建List集合对象
List list = new ArrayList();
// 添加元素
list.add("hello");
list.add("world");
list.add("java"); // 方式1:迭代器迭代元素,迭代器修改元素
// 而Iterator迭代器却没有添加功能,所以我们使用其子接口ListIterator
ListIterator lit = list.listIterator();
while (lit.hasNext()) {
String s = (String) lit.next();
if ("world".equals(s)) {
lit.add("javaee");
}
}
System.out.println("list:" + list);
}
}
执行结果:
从结果看出:元素是跟在刚才迭代的元素后面的。
B的解决方案:
public class ListIteratorDemo1 { public static void main(String[] args) {
// 创建List集合对象
List list = new ArrayList();
// 添加元素
list.add("hello");
list.add("world");
list.add("java"); // 方式2:集合遍历元素,集合修改元素(普通for)
for (int x = 0; x < list.size(); x++) {
String s = (String) list.get(x);
if ("world".equals(s)) {
list.add("javaee");
}
} System.out.println("list:" + list); } }
执行结果:
从结果看出:元素在最后添加的。
Exception in thread "main" java.util.ConcurrentModificationException解决方案的更多相关文章
- Exception in thread "main" java.util.ConcurrentModificationException
package test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public c ...
- Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 0 [ ^
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character clas ...
- Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 0 解决方法: 要对切割字符进行转义\\
使用str.split("[",15)时,出现Exception in thread "main" java.util.regex.PatternSyntaxE ...
- Exception in thread "main" java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for topic_test_1219-2: 30010 ms has passed since batch creatio
代码如下 public static void producer1() throws ExecutionException, InterruptedException { Properties pro ...
- Exception in thread "main" java.util.InputMismatchException
今天写代码来了一个异常 /** * 需求分析:根据输入的天数是否是周六或是周日, * 并且天气的温度大于28摄氏度,则外出游泳,否则钓鱼 * @author chenyanlong * 日期:2017 ...
- unit测试出现异常:Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.commons.util
在进行单元测试时,测试出现异常 Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform ...
- 解决方案--java执行cmd命令ProcessBuilder--出错Exception in thread "main" java.io.IOException: Cannot run program "dir d:\": CreateProcess error=2(xjl456852原创)
当我尝试在java中通过ProcessBuilder运行window的cmd命令时出现错误: public static void main(String [] args) throws IOExce ...
- WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Exception in thread "main" java.io.IOException: No FileSystem for sc F
1.执行脚本程序报如下所示的错误: [hadoop@slaver1 script_hadoop]$ hadoop jar web_click_mr_hive.jar com.bie.hive.mr.C ...
- Exception in thread "main" java.lang.StackOverflowError at java.util.ArrayList$SubList.rangeCheckForAdd(Unknown Source)
Exception in thread "main" java.lang.StackOverflowError at java.util.ArrayList$SubList.ran ...
随机推荐
- aspnet core 全局模型验证,统一api响应
上手就来 新建一个模型验证过滤器,其中ApiResp是自定义的统一响应类. public class VldFilter:IActionFilter { /// <summary> /// ...
- java 框架-企业级搜索 Solr
https://blog.csdn.net/cs_hnu_scw/article/details/79388080 一:Solr简介 Solr是一个独立的企业级搜索应用服务器,它对外提供类 ...
- 正则限制input负数输入
//直接在input标签内加入下面两个事件处理程序即可 onkeyup="this.value=this.value.replace(/\D|^0/g,'')" onafterpa ...
- 全面聊聊JavaScript的浅拷贝和深拷贝
一.背景 首先我们可以看下面这段简单的代码: var obj = {name:'程序猿',sex:'男'}; var arr = ['程序猿','程序媛']; var copyobj = o ...
- laravel 的安装与配置
1.工作环境 php 7.0+ .MySQL5.1+ 这里可以用开发环境包一键安装: 自己用的是wamp(windows)http://www.wampserver.com/en/ linux系统和m ...
- 2.Buffer 缓冲区
/*缓冲区(Buffer)*/ Buffer 就像一个数组,可以保存多个相同类型的数据.根据数据类型不同(boolean 除外),有以下Buffer常用子类: /*ByteBuffer*/(常用) . ...
- [LeetCode] 328. Odd Even Linked List ☆☆☆(奇偶节点分别放一起)
每天一算:Odd Even Linked List 描述 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起.请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性. 请尝 ...
- depth/stencil buffer的作用 ----------理解模板缓存 opengl
在D3D11中,有depth/stencil buffer,它们和framebuffer相对应,如下图所示,framebuffer中一个像素,有相对应的depth buffer和stencil buf ...
- mongodb模式模型设计及编码-Mongoose
走到这一步,我们的网站还不能称为动态的网站,因为所要的数据都是伪造的,所以现在要对数据库的模型进行设计 Mongoose 我们用到的工具模块是Mongoose,他能对Mongodb进行建模的这样一 ...
- 大数据之路week04--day06(I/O流阶段一 之异常)
从这节开始,进入对I/O流的系统学习,I/O流在往后大数据的学习道路上尤为重要!!!极为重要,必须要提起重视,它与集合,多线程,网络编程,可以说在往后学习或者是工作上,起到一个基石的作用,没了地基,房 ...