散列表获取并发修改异常的问题 [英] issue with hashmap getting concurrent modification exception
本文介绍了散列表获取并发修改异常的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
原因是:java使用map和执行一些remove,如何避免这种情况? .util.ConcurrentModificationException在$ java.util.HashMap
$ HashIterator.nextEntry(HashMap.java:793)$ b $在java.util.HashMap $ EntryIterator.next(HashMap.java:834)
在java.util.HashMap $ EntryIterator.next(HashMap.java:832)
映射< FormField,Object> ItemMap = domainItem.getValues(); (Map.Entry< FormField,Object> ValMap:ItemMap.entrySet()){
List< Field> groupIdList = Mapper.getGroupId(groupFieldId);
for(Field field:groupIdList){
ItemMap.put(new FormField(field),domainItem.getDomainItemLinkId());
}
ItemMap.remove(ValMap.getKey());
}
解决方案
更新:
使用Iterator和 ConcurrentHashMap
来避免这种情况
t抛出异常
映射< Integer,String> map = new ConcurrentHashMap< Integer,String>();
map.put(1,a);
map.put(2,b);
map.put(3,c);
map.put(4,d);
for(Iterator< Integer> keys = map.keySet()。iterator(); keys.hasNext();){
Integer key = keys.next();
String val = map.get(key);
map.remove(key);
$ / code>
或者在迭代时使用另一个映射,并在最后将其复制到源<例如:
Map< Integer,String> dummy = new HashMap< Integer,String>();
map.put(1,a);
map.put(2,b);
map.put(3,c);
map.put(4,d);
dummy.putAll(map);
for(Iterator< Integer> keys = dummy.keySet()。iterator(); keys.hasNext();){
Integer key = keys.next();
String val = map.get(key);
map.remove(key);
}
System.out.println(map);
I am getting the below error while using map and performing some remove.How to avoid this ?
Caused by: java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$EntryIterator.next(HashMap.java:834)
at java.util.HashMap$EntryIterator.next(HashMap.java:832)
Map<FormField, Object> ItemMap = domainItem.getValues();
for (Map.Entry<FormField, Object> ValMap : ItemMap.entrySet()) {
List<Field> groupIdList = Mapper.getGroupId(groupFieldId);
for (Field field : groupIdList) {
ItemMap.put(new FormField(field), domainItem.getDomainItemLinkId());
}
ItemMap.remove(ValMap.getKey());
}
解决方案
Update:
Use Iterator and ConcurrentHashMap
to avoid this scenario
Following won't throw exception
Map<Integer, String> map = new ConcurrentHashMap<Integer, String>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
for (Iterator<Integer> keys = map.keySet().iterator(); keys.hasNext();) {
Integer key = keys.next();
String val = map.get(key);
map.remove(key);
}
or use another map while iterating and at the end copy it to source
for example:
Map<Integer, String> dummy = new HashMap<Integer, String>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
dummy.putAll(map);
for (Iterator<Integer> keys = dummy.keySet().iterator(); keys.hasNext();) {
Integer key = keys.next();
String val = map.get(key);
map.remove(key);
}
System.out.println(map);
这篇关于散列表获取并发修改异常的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文