关于map.keySet()的返回值不能使用for-each循环的问题
Map<String, Object> map = this.interfaceManagementDao.getTicket(paramMap.get("TICKET_ID").toString());
Set<String> set = map.keySet();
for (String key : map.keySet()) {
if(map.get(key) == null || "null".equals(map.get(key))){
map.remove(key);
}
}
这段代码主要是想将map中所有value值为null的键值对删除,但是运行时会抛出下面的异常
ava.util.ConcurrentModificationException: null
看了源码后发现map.keySet()返回的是一个Set集合,在HashMap中是这么写的
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
用的是它的父类AbstractMap中的keySet
transient Set<K> keySet;
而在下面代码中for-each循环中的map.keySet() 指向了这个map中的keySet
在调用 map.remove(key);方法时map 中的 keySet的数据就会改变,这时迭代器就会报ConcurrentModificationException 异常
for (String key : map.keySet()) {
找到原因后就好解决了
Map<String, Object> map = this.interfaceManagementDao.getTicket(paramMap.get("TICKET_ID").toString());
Set<String> set = map.keySet();
Object[] strings = set.toArray();
for (Object key : strings) {
if(map.get(key.toString()) == null || "null".equals(map.get(key.toString()))){
map.remove(key);
}
}
但是我又碰到了个问题
在 Object[] strings = set.toArray();处本来是想用String数组的,但是不知道为什么用String数组就报错,只能用Object数组凑合着用了
有没有大神出来解答一下
如有错漏之处请多多指教