梦幻之旅

DEBUG - 天道酬勤

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  671 随笔 :: 6 文章 :: 256 评论 :: 0 Trackbacks
问题:
下面的代码试图利用
HashMap的Iterator对象遍历该HashMap并删除满足条件的元素(比如超时的元素),但会抛出java.util.ConcurrentModificationException异常
    public static void main(String[] args)
        
        HashMap<String, String> hs=new HashMap();    
        hs.put("p1", "1");
        hs.put("p2", "1");
        hs.put("p3", "1");
        hs.put("p4", "1");
        hs.put("p5", "1");
        hs.put("p6", "1");       
        Iterator it=hs.keySet().iterator();      
        while(it.hasNext())
        {
            String str=(String)it.next();               
            System.out.println(hs);   

             //逻辑处理.........         
             .............
            hs.remove(str);      
         
}
    原因应该
hs.remove(str)后,it内容没变,并且it里的指针列表又重新排序,所以只要确保删除任一元素后,it保持同步更新即可:
    解决方案一:
删除任一元素后,it保持同步更新
    ............
      
Iterator it=hs.keySet().iterator();   
        while(it.hasNext())
        {
            it=hs.keySet().iterator();  
            String str=(String)it.next();               
            System.out.println(hs);   

             //逻辑处理.........         
             .............
            hs.remove(str);      
         

    ...........
    这样的时间复杂度明显太大(两层循环嵌套)
    解决方案二:
由于删除元素时,hs的iterator对象也重新排序,所以只要用hs的一个副本hsBack
Uackp的iterator去遍历hs即可,这样在删除hs元素时iterator就不会重排了(因为删除的是hs的元素,而不是该iterator所属的
hsBackUackp
...................
        hsBackUp=(HashMap<String, String>)hs.clone();
        Iterator it=hsBackUp.keySet().iterator();
        System.out.println(hsBackUp);
        while(it.hasNext())
        {
            String str=(String)it.next();               
            System.out.println(hs);               
            hs.remove(str);       
         
.....................
    这样虽然时间复杂度小了(只有一层循环),可是空间复杂度大了(多了一个hashmap的拷贝);
    查阅api文档和相关资料后,原来iterator对象有一remove方法:
void remove()       
Removes from the underlying collection the last element returned by the
iterator (optional operation). This method can be called only once per
call to
next. The behavior of an iterator is unspecified if
the underlying collection is modified while the iteration is in
progress in any way other than by calling this method.

于是有下面的改进:
解决方案三:
..............................
Iterator it=hs.keySet().iterator();
while(it.hasNext())
{
String str=(String)it.next();
System.out.println(hs);
it.remove();
}
..............................
posted on 2011-11-05 01:42 HUIKK 阅读(16099) 评论(1)  编辑  收藏 所属分类: Java

评论

# re: 利用java迭代器Itetator遍历并删除HashMap中的元素问题 2014-11-25 09:47 柳qing
本来简单的东西被楼主讲复杂了。。。  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: