---
title: "java.util.ConcurrentModificationException解决"
author: "suky"
date: "2010-11-30T14:55:52Z"
tags: []
categories: ["编程语言"]
slug: "java-util-concurrentmodificationexception"
draft: false
lastmod: "2010-11-30T14:55:52Z"
id: 829354
url: "https://suky.iteye.com/blog/829354"
---

遍历集合时要注意的地方：不可以对改集合相关的地方做添加或删除操作。

```
for(Map.Entry<String, String> m:foMap.entrySet()){

...
foMap.remove(m.getKey());
...

}
```

 

      运行类似这样的代码，就会抛java.util.ConcurrentModificationException异常。

解决方法可以是: 在遍历时用一个集合存放要删除的对象,在遍历完后,调用

 

removeAll(Collection&lt;?&gt; c)

```
Collection<String> removeC = new ArrayList<String>();
for(Map.Entry<String, String> m:foMap.entrySet()){

...
removeC.add(m.getKey());
...
}
if(removeC.size()!=0) foMap.keySet().removeAll(removeC);
```