Java处理java.util.ConcurrentModificationException异常
代码:
public static void reduce(HashMap<String, Integer> hashMap, final Integer count) { Iterator<String> iter = hashMap.keySet().iterator(); String key; while(iter.hasNext()) { key = iter.next(); if (!hashMap.get(key).equals(count)) { hashMap.remove(key); } } return hashMap; }
异常:
Exception in thread "main" java.util.ConcurrentModificationException
原因:
在迭代的过程中进行了add(),remove()操作。其实仔细想想也能理解,如果在迭代中使用remove(),那第二轮循环时的next()究竟指向谁?!
方法:
使用迭代器对象来移除该对象.
public static void reduce(HashMap<String, Integer> hashMap, final Integer count) { Iterator<String> iter = hashMap.keySet().iterator(); String key; while(iter.hasNext()) { key = iter.next(); if (!hashMap.get(key).equals(count)) { // hashMap.remove(key);
iter.remove(); // 这里改用迭代器对象来移除! } } return hashMap; }