容器遍历删除问题

    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();其实刚开始我是以为删除之后迭代器没有更新导致的

原文地址:https://www.cnblogs.com/bashala/p/3591567.html