Posted on 2008-03-25 10:34
七郎归来 阅读(1093)
评论(0) 编辑 收藏
在对一个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)) {
m.remove(sessionId);
iterator.remove(); //这行代码是关键,使循环知道m大小已经改变
}
}
System.out.println(m.get("ggg"));
System.out.println(m.get("lizongbo"));
System.out.println(m.get("544"));
}