• List循环遍历时移出元素


    普通的增强for循环遍历时移出元素报错

    package com.fridge.controller.cms;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @program: mythicalanimals
     * @description: 集合遍历时移出元素demo
     * @author: TheEternity Zhang
     * @create: 2020-06-08 14:27
     */
    public class ListIteratorDemo {
        public static void main(String[] args) {
            List<String> list = new ArrayList<>();
            list.add("abc");
            list.add("abe");
            list.add("hgf");
            list.add("zzx");
            for (String str: list) {
                if(str.contains("a")){
                    list.remove(str);
                }else{
                    System.out.println(str);
                }
            }
            System.out.println("集合的数量:"+list.size());
        }
    }
    

    抛出ConcurrentModificationException异常

    Connected to the target VM, address: '127.0.0.1:62068', transport: 'socket'
    Exception in thread "main" java.util.ConcurrentModificationException
    	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
    	at java.util.ArrayList$Itr.next(ArrayList.java:859)
    	at com.fridge.controller.cms.ListIteratorDemo.main(ListIteratorDemo.java:19)
    Disconnected from the target VM, address: '127.0.0.1:62068', transport: 'socket'
    

    使用Iterator在遍历时移出元素

    package com.fridge.controller.cms;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    /**
     * @program: mythicalanimals
     * @description: 集合遍历时移出元素demo
     * @author: TheEternity Zhang
     * @create: 2020-06-08 14:27
     */
    public class ListIteratorDemo {
        public static void main(String[] args) {
            List<String> list = new ArrayList<>();
            list.add("abc");
            list.add("abe");
            list.add("hgf");
            list.add("zzx");
            Iterator<String> iterator = list.iterator();
            while (iterator.hasNext()){
                String str = iterator.next();
                if(str.contains("a")){
                    iterator.remove();
                }else{
                    System.out.println(str);
                }
            }
            System.out.println("集合的数量:"+list.size());
        }
    }
    
    

    结果

    hgf
    zzx
    集合的数量:2
    
  • 相关阅读:
    ios开发启动页面
    C++再学习之路(五)
    C++再学习之路(四)
    opencv再学习之路(九)---制作对焦图像
    opencv再学习之路(八)---轮廓检测
    C++再学习之路---例程(一) 文本查询
    opencv再学习之路(五)---灰度直方图显示
    opencv再学习之路(七)---图像单个元素的访问
    opencv再学习之路(六)---模板匹配
    C++再学习之路(三)
  • 原文地址:https://www.cnblogs.com/eternityz/p/13595801.html
Copyright © 2020-2023  润新知