java知识体系

5、HashMap如何避免ConcurrentModificationException异常的发生?


解决办法:使用迭代器的remove方法而不是使用集合的remove方法
package com;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class TestHashMapFastFail2
{
    public static void main(String[] args)
    {
        System.out.println("test solve HashMap fast-fail");
        Map<Integer, String> testHashMap = new HashMap<Integer, String>();
        testHashMap.put(1000, "1000");
        testHashMap.put(2000, "2000");
        testHashMap.put(3000, "3000");
        testHashMap.put(4000, "4000");
        testHashMap.put(5000, "5000");
        System.out.println(testHashMap.size());
        Iterator iterator = testHashMap.entrySet().iterator();
        while (iterator.hasNext())
        {
            int key = (int)((Map.Entry)iterator.next()).getKey();
            System.out.println("key=" + key);
            if (key == 2000 || key == 4000)
            {
                iterator.remove();
            }
        }
        System.out.println(testHashMap.size());
        for (Map.Entry<Integer, String> entry : testHashMap.entrySet())
        {
            System.out.println(entry.getKey() + "-->" + entry.getValue());
        }
    }
}

结果:
test solve HashMap fast-fail
5
key=2000
key=4000
key=1000
key=3000
key=5000
3
1000-->1000
3000-->3000
5000-->5000