zoukankan      html  css  js  c++  java
  • 容器遍历删除问题

        Map<String,Integer> m1=new HashMap<String,Integer>();
            m1.put("one", 1);
            m1.put("two",2);
            m1.put("three", 3);
            Set<String> s=m1.keySet();
                
            Iterator<String> it=s.iterator();
            
            while(it.hasNext()){
                String s1=it.next();
                if("two".equals(s1)){
                    s.remove(s1);
                    //it.remove();
                }
                //System.out.println(it.next());
            }

    这时会抛异常

    Exception in thread "main" java.util.ConcurrentModificationException

    解决方法

        Map<String,Integer> m1=new HashMap<String,Integer>();
            m1.put("one", 1);
            m1.put("two",2);
            m1.put("three", 3);
            Set<String> s=m1.keySet();
                
            Iterator<String> it=s.iterator();
            
            while(it.hasNext()){
                String s1=it.next();
                if("two".equals(s1)){
                    //s.remove(s1);
                    it.remove();
                }
                //System.out.println(it.next());
            }

    而当我重新遍历的时候

        System.out.println(it.hasNext());
            while(it.hasNext()){
            System.out.println(it.next());

    打印出来的是false,因为while遍历是游标已经到结尾了,再调用it.hasNext()是false

    修改

        it=s.iterator();
            System.out.println(it.hasNext());
            while(it.hasNext()){
            System.out.println(it.next());

    加了一段it=s.iterator();其实刚开始我是以为删除之后迭代器没有更新导致的

  • 相关阅读:
    pycharm上传代码到码云(详细)
    我是如何理解ThreadLocal
    前两次成绩汇总
    第五次作业
    第四次作业
    第三次作业
    第二次作业
    第一次作业
    单例模式之懒汉式与饿汉式
    浅谈对srping框架的理解
  • 原文地址:https://www.cnblogs.com/bashala/p/3591567.html
Copyright © 2011-2022 走看看