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

posted on 2014-03-10 13:04  xxyyjj  阅读(172)  评论(0编辑  收藏  举报