zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    HBase- 安装单机版HBase
    javascript中的设计模式之模板方法模式
    win 设置自动启动软件
    php高精度加减乘除
    frp实现内网穿透,实现夸服务器访问
    OCM 12c 直考预备知识点
    Oracle 19c New Features : Active Data Guard DML Redirect
    3级搭建类302-Oracle 19c RAC 双节点搭建
    VMWare WorkStation 15.5 配置RAC共享存储节点二无法识别共享磁盘UUID解决办法
    你还在争论 count(*) 与 count(column) 哪个更快?
  • 原文地址:https://www.cnblogs.com/eternityz/p/13595801.html
Copyright © 2011-2022 走看看