java.util.ConcurrentModificationException产生原因及解决方法

java.util.ConcurrentModificationException产生原因及解决办法
第一次遇到此异常是在处理3g.renren.com的好友分组功能中,因为接口提供的好友分组(以map的方式提供好友分组的id跟分组名)中没有把分组名为空,但是id存在的数据屏蔽掉,所以我在调用接口服务之后,需要重新处理value为空的数据。
代码如下:
view plain
import java.util.HashMap;  
import java.util.Map;  
  
/** 
 *  
 * Dec 1, 2011 
 * @author 车前猛跑 
 */  
public class MapDemo {  
  
    public static void main (String [] args) {  
        Map<Integer, String> map = new HashMap<Integer, String>();  
        map.put(5, null); //①  
        //map.put(1, "a"); //②  
        //map.put(3, null); //③  
          
        MapDemo md = new MapDemo();  
        md.clearMap(map);  
        for (Map.Entry<Integer, String> entry : map.entrySet()) {  
            System.out.println(entry.getKey());  
        }  
        if (map.isEmpty()) {  
            System.out.println("empty");  
        }  
    }  
      
    private void clearMap (Map<Integer , String> map) {  
        for (Map.Entry<Integer, String> entry : map.entrySet()) {  
            if (entry.getValue() == null) {  
                map.remove(entry.getKey());  
            }  
        }  
    }  
}  

上述代码中有①②③三处注释,
情况1:下面我们让②③都注释上,代码运行后不出错(自己运行,这里不贴出运行结果了),
情况2:注释掉①,②③不注释,代码运行后也不出错
情况3:①②③不注释,运行代码后出错,比较一下就知道了区别了,这种情况中,map被中有2个value为空的数据,所以map会被remove2次。
原因:对map进行修改操作是,下一次的修改会被认为是对原对象的修改,而其实被修改的对象已经不是原对象了,所以会造成当前修改异常java.util.ConcurrentModificationException。
知道原因就好解决了,解决办法自己想吧,哈。

下面是我所用到的解决办法,比较土。应该也还有别的方法可以解决该问题。
view plain
/**  
 *   
 * Dec 1, 2011  
 * @author 车前猛跑  
 */  
public class MapDemo {  
  
    public static void main (String [] args) {  
        Map<Integer, String> map = new HashMap<Integer, String>();  
        map.put(5, null); //①  
        map.put(1, "a"); //②  
        map.put(3, null); //③  
          
        MapDemo md = new MapDemo();  
        Map<Integer , String> newmap = md.clearMap(map); // 通过新map返回数据  
        for (Map.Entry<Integer, String> entry : newmap.entrySet()) {  
            System.out.println(entry.getKey());  
        }  
        if (map.isEmpty()) {  
            System.out.println("empty");  
        }  
    }  
      
    private Map<Integer , String> clearMap (Map<Integer , String> map) {  
        Map<Integer , String> retmap = new HashMap<Integer , String>();  
        for (Map.Entry<Integer, String> entry : map.entrySet()) {  
            if (entry.getValue() != null) {  
                retmap.put(entry.getKey(), entry.getValue());  
            }  
        }  
        return retmap; // 通过新map返回数据  
    }  
}  

问题解决了。