zoukankan      html  css  js  c++  java
  • 如何在Map 遍历过程中,删除一个元素?

    package ee;
    
    import java.util.HashMap;
    import java.util.Iterator;
    
    public class Demo {
        public static void main(String[] args) {
            HashMap<Integer, Integer> count = new HashMap<Integer, Integer>();
            count.put(1,11);
            count.put(2,22);
            count.put(3,33);
            //错误的 会抛出异常 ----ConcurrentModificationException
          /* for (Integer i : count.keySet()) {
                if(i == 2){
                    count.remove(i);
                }
                System.out.println(i);
            }*/
            //正确的    it.remove();  // 这个可以实现 遍历的过程中删除某个元素
           Iterator<Integer> it = count.keySet().iterator();
            while(it.hasNext()) {
                Integer key = it.next();
                if(key == 2){
                    it.remove();  // 这个可以实现 遍历的过程中删除某个元素
                }
                if(key == 3){
                    count.put(key, 44);
                }
            }
    
            for (Integer value : count.values()) {
                System.out.println(value);
            }
    
    
        }
    
    }
    

     参考文档:

    https://www.cnblogs.com/cherish010/p/9178085.html
    https://blog.csdn.net/u011517841/article/details/82955498

  • 相关阅读:
    二维数组排序
    正则验证
    yii2视频教材
    yii2数据库简单操作
    MySQL(zip版)安装教程
    OpenCV插件
    机器视觉项目总结——光源
    VS2017运行YOLOv4
    VS打开cmd(直接在项目路径)
    【转载】Win10安装Ubuntu子系统
  • 原文地址:https://www.cnblogs.com/william-dai/p/15064368.html
Copyright © 2011-2022 走看看