---
title: "Map遍历java.util.ConcurrentModificationException异常"
author: "mib168"
date: "2011-12-12T15:26:27Z"
tags: []
categories: ["编程语言"]
slug: "map-java-util-concurrentmodificationexception"
draft: false
lastmod: "2011-12-12T15:26:27Z"
id: 1306530
url: "https://mib168.iteye.com/blog/1306530"
---

在

for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {

。。。。。

dKeyObjectMap.remove(key);

 

}

后在执行了remove方法之后，再去执行循环，iter.next()的时候（当然，如果remove的是最后一条，就不会再去执行next()操作了）

所以，产生ConcurrentModificationException的原因就是：  
执行remove(Object o)方法之后，modCount和expectedModCount不相等了。然后当代码执行到next()方法时，判断了checkForComodification()，发现两个数值不等，就抛出了该Exception。  
要避免这个Exception，就应该使用remove()方法。