当前位置: 代码迷 >> J2SE >> ConcurrentModificationException的事例
  详细解决方案

ConcurrentModificationException的事例

热度:77   发布时间:2016-04-23 20:32:15.0
ConcurrentModificationException的例子
public class MapIterator {

    public static void main(String[] args) {

        Map<String, String> map = new HashMap<String, String>();
        map.put("a", "tangsc");
        map.put("b", "songyuanyuan");

        System.out.println("HashMap before iterator: " + map);
        Iterator<String> it1 = map.keySet().iterator();
        while (it1.hasNext()) {
            String key = it1.next();
            if (key.equals("a")) {
                map.put("c", "name");
            }
        }
        System.out.println("HashMap after iterator: " + map);


    }


}


大家看看,为什么我这段代码不会引起ConcurrentModificationException,好奇怪
------解决方案--------------------
这个是巧合而已,楼主说的对,没出错仅仅是因为放入c后,c不是位于迭代器的最后一个位置,循环结束了,把key.equals("a")改成key.equals("b")的话,那看来百分百出错。因为迭代时校验的两个值,预期数,和实际数,在这个时候不相等了,就i抛出异常了。