zoukankan      html  css  js  c++  java
  • 29.2 Iterator 迭代器ConcurrentModificationException:并发修改异常处理

    /*
    * Iterator:迭代器
    *
    * 需求:判断集合中是否包含元素java,如果有则添加元素android
    * Exception in thread "main" java.util.ConcurrentModificationException:并发修改异常
    * 迭代器是依赖于集合的,相当于集合的一个副本,当迭代器在操作的时候,如果发现和集合不一样,则抛出异常
    *
    * 解决方案:
    * 在使用迭代器进行遍历的时候使用迭代器来进行修改
    * */

    public class IteratorDemo2 {
        public static void main(String[] args) {
    //        method();
    //        concurrentModificationExceptionMethod();
            method2();
    
    
        }
    
        private static void method2() {
            //创建集合对象
    //        Collection c = new ArrayList();
            List c = new ArrayList();
            //添加元素
            c.add("hello");
            c.add("world");
            c.add("java");
            //通过遍历获取集合中的元素,判断集合中是否包含元素java
            //使用迭代器添加元素
    //        Iterator it = c.iterator();
            ListIterator it = c.listIterator();
            while (it.hasNext()) {
                if(it.next().equals("java")) {
    //                it.add //Iterator没有add方法,使用其子类方法。List.listIterator
                    it.add("android");
                }
            }
    
            System.out.println(c);
        }
    
        private static void concurrentModificationExceptionMethod() {
            //创建集合对象
            Collection c = new ArrayList();
            //添加元素
            c.add("hello");
            c.add("world");
            c.add("java");
            //通过遍历获取集合中的元素,判断集合中是否包含元素java
            Iterator it = c.iterator();
            while (it.hasNext()) {
                if(it.next().equals("java")) {
                    //使用集合添加元素
                    c.add("android");
                }
            }
        }
    
        private static void method() {
            //创建集合对象
            Collection c = new ArrayList();
            //添加元素
            c.add("hello");
            c.add("world");
            c.add("java");
            //判断集合中是否包含元素java
            if(c.contains("java")) {
                c.add("android");
            }
    
            System.out.println(c);
        }
    }

    输出

  • 相关阅读:
    Android控件系列之RadioButton&RadioGroup
    清理android桌面
    GPRS无限流量卡
    Android权限大全1
    android权限大全
    猎豹免费WIFI怎么用
    100%参考点总结
    手机淘宝flexible布局探索及最终方案
    (持续更新中)移动端web开发兼容总结
    (持续更新)浏览器兼容性总结—之前端开发常用属性及api
  • 原文地址:https://www.cnblogs.com/longesang/p/11264344.html
Copyright © 2011-2022 走看看