我想判断一个集合里面有没有"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解决方案的更多相关文章

  1. Exception in thread "main" java.util.ConcurrentModificationException

    package test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public c ...

  2. 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 ...

  3. 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 ...

  4. 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 ...

  5. Exception in thread "main" java.util.InputMismatchException

    今天写代码来了一个异常 /** * 需求分析:根据输入的天数是否是周六或是周日, * 并且天气的温度大于28摄氏度,则外出游泳,否则钓鱼 * @author chenyanlong * 日期:2017 ...

  6. unit测试出现异常:Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.commons.util

    在进行单元测试时,测试出现异常 Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform ...

  7. 解决方案--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 ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. VS2017清除工具、用于清除Microsoft Visual Studio最近打开项目

    最近每天在用VS2017,但是每次打开它都会弹出最近项目的记录,很是烦人. 最主要是我不想别人得知我最近的项目和项目进度,每次加密项目会比较麻烦. 所以经过简单的研究,编写了这个小工具,打开直接单击就 ...

  2. echarts重写图例点击事件

    echarts version: 3.1.2 修改图例点击事件样例代码: 当第一次点击图例时,只显示点击的图例. 当还剩一个图例被取消选中后,自动全选中所有图例. var triggerAction ...

  3. friend

    #include <iostream> using namespace std; //friend 友元,效率的问题 //get 方法和set方法,是标准封装的结果,friend破坏了这种 ...

  4. [LeetCode] 46. Int数组全排列 ☆☆☆(回溯)

    描述 给定一个没有重复数字的序列,返回其所有可能的全排列. 示例: 输入: [1,2,3]输出:[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2, ...

  5. 转:IDEA中如何使用debug调试项目 一步一步详细教程

    原文链接:http://www.yxlzone.top/show_blog_details_by_id?id=2bf6fd4688e44a7eb560f8db233ef5f7 在现在的开发中,我们经常 ...

  6. django 新项目

    1.创建虚拟环境 mkvirtualenv - p  python3 2.pycharm : 在pycharm中新建项目, 取名.添加虚拟机上的虚拟环境

  7. python django uwsgi nginx安装

    python django uwsgi nginx安装 已安装完成python/django的情况下安装 pip install uwsgi cd /usr/share/nginx/html/ vim ...

  8. Spotlights【思维+前缀和优化】

    https://blog.csdn.net/mengxiang000000/article/details/53291883   原博客地址 http://codeforces.com/group/1 ...

  9. Java字节码方法表与属性表深度剖析

    方法表: 在上一次咱们已经分析到了字段信息了,如下: 紧接着就是方法相关的信息了: 而它展开之后的结构为: 所以往后数2个字节,看一下方法的总数: 3个方法,可咱们只定义了两个方法呀: 因为编译器会为 ...

  10. Please, commit your changes or stash them before you can merge. Aborting

    1.stash 通常遇到这个问题,你可以直接commit你的修改:但我这次不想这样. 看看git stash是如何做的. git stash    git pull    git stash pop ...