利用java迭代器Itetator遍历并删除HashMap中的元素问题

来源:互联网 发布:大数据视频教程51CTO 编辑:程序博客网 时间:2024/06/05 02:37
问题:
下面的代码试图利用
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();          }   ..............................
原创粉丝点击