zoukankan      html  css  js  c++  java
  • 关于集合越界后 不能使用迭代器遍历的处理方式

    迭代器的并发修改异常
    迭代器的并发修改异常 java.util.ConcurrentModificationException
    就是在遍历的过程中,使用了集合方法修改了集合的长度,不允许的

    原因
    运行上述代码发生了错误 java.util.ConcurrentModificationException这是什么原因呢?
    在迭代过程中,使用了集合的方法对元素进行操作。
    导致迭代器并不知道集合中的变化,容易引发数据的不确定性。

    并发修改异常解决办法:
    在迭代时,不要使用集合的方法操作元素。
    或者通过ListIterator迭代器操作元素是可以的,ListIterator的出现,解决了使用Iterator迭代过程中可能会发生的错误情况。代码如下。

    public class Demo3_List {

    /**
    ** A:案例演示
    * 需求:我有一个集合,请问,我想判断里面有没有"world"这个元素,如果有,我就添加一个"javaee"元素,请写代码实现。
    */
    public static void main(String[] args) {
    List list = new ArrayList();
    list.add("a"); //Object obj = new String();
    list.add("b");
    list.add("world");
    list.add("c");
    list.add("d");
    list.add("e");

    /*Iterator it = list.iterator(); //获取迭代器
    while(it.hasNext()) { //判断集合中是否有元素
    String str = (String)it.next(); //向下转型
    if("world".equals(str)) {
    list.add("javaee"); //遍历的同时在增加元素,并发修改ConcurrentModificationException
    }
    }*/

    ListIterator lit = list.listIterator(); //获取迭代器(List集合特有的)
    while(lit.hasNext()) {
    String str = (String)lit.next(); //向下转型
    if("world".equals(str)) {
    //list.add("javaee"); //遍历的同时在增加元素,并发修改ConcurrentModificationException
    lit.add("javaee");
    }
    }

    System.out.println(list);
    }

    }

  • 相关阅读:
    将纸质照片转成数字报名照
    华为手机如何下载google play商店中的apk
    大疆Mavic 2发布
    [转] Spring使用Cache、整合Ehcache
    [转] spring-boot集成swagger2
    [转] Intellij IDEA快捷键与使用小技巧
    [转] 这个常识很重要,教你如何区分JEDEC 1600内存与XMP 1600内存
    [转] 下载文件旁边附的MD5/SHA256等有什么用途?
    Openresty 健康检查
    Vuforia图像追踪,动态创建的对象隐藏显示的坑
  • 原文地址:https://www.cnblogs.com/lijun6/p/10386563.html
Copyright © 2011-2022 走看看