Java concurrent modification exception

和自甴很熟 提交于 2020-01-11 09:45:08

问题


I have written following code which is resulting in concurrent modification exception. How can I prevent it ? The idea is to escape all values of the Map and reconstruct the object (dO) back with new param map.

    try {
        Map<String,String[]> paramMap = dO.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = paramMap.entrySet();
        Iterator<Map.Entry<String, String[]>> it = entries.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String[]> entry = it.next();
            String[] values = entry.getValue();
            List<String> valList = new ArrayList<String>();
            if (values != null) {
                for (String value : values) {
                    valList.add(escapeHTML(value));
                     }
                dO.removeParameter(entry.getKey());

//Please note that Parameter is a hashMap so , Is it required to remove the entry first before inserting or it will replace the new value associated with key . How it works in Java ?

                dO.addParameter(entry.getKey(),valList.toArray(new String[valList.size()]));
               }
            }
        }

回答1:


the exception is thrown because you are adding/removing things from the map while you are iterating it:

dO.removeParameter(entry.getKey());
dO.addParameter(entry.getKey(),valList.toArray(new String[valList.size()]

you should use iterator.remove() instead.




回答2:


Not sure you need to alter the keys of Map, it appears all you want to do is alter the values in the arrays.

for(String[] values: dO.getParameterMap().values()) 
    for (int i = 0; i < values.length; i++) 
        values[i] = escapeHTML(values[i]);

I would make sure the Map does have null values stored. But if you can't change this you will need to add if(values != null)




回答3:


You should remove/add only if you are changing a key in a map. As I see in the code, you are changing only value. Hence you could use entry.setValue(...) instead.



来源:https://stackoverflow.com/questions/8090398/java-concurrent-modification-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!