在对一个map进行迭代遍历并删除一些符合条件的键值对的时候,容易出现
java.util.ConcurrentModificationException 这个异常。
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:787)
at java.util.HashMap$KeyIterator.next(HashMap.java:823)
解决办法如下:
import java.util.*;
public class TestMap {
public TestMap() {
}
public static void main(String[] args) {
java.util.Map m = new java.util.HashMap();
m.put("aaa", "lizongbo ");
m.put("bbb", " lizongbo");
m.put("ccc", "lizongbo ");
m.put("ddd", " lizongbo");
m.put("eee", "lizongbo");
m.put("fff", "lizongbo");
m.put("ggg", "lizongbo");
m.put("adads", "lizongbo");
m.put("dffd", "lizongbo");
m.put("dcxv", "lizongbo");
m.put("lizongbo", "lizongbo");
m.put("ert", "lizongbo");
m.put("544", "lizongbo ");
Iterator iterator = m.keySet().iterator();
while (iterator.hasNext()) {
String sessionId = (String) iterator.next();
if ("ggg".equals(sessionId) || "lizongbo".equals(sessionId) ||
"544".equals(sessionId)) {
iterator.remove(); //这行代码是关键。
m.remove(sessionId);
}
}
System.out.println(m.get("ggg"));
System.out.println(m.get("lizongbo"));
System.out.println(m.get("544"));
}
相关参考: http://ldfren.bosinet.com/archives/113.html
http://gceclub.sun.com.cn/yuanchuang/week-14/iterator.html