首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ConcurrentModificationException - HashMap

ConcurrentModificationException - HashMap
EN

Stack Overflow用户
提问于 2016-10-07 15:48:43
回答 1查看 448关注 0票数 1

请考虑以下代码。

代码语言:javascript
复制
Map<Integer,String> map = new HashMap<Integer, String> (5);
map.put(1, "a");
map.put(2, null);
map.put(3, "b");
map.put(4, "e");
for (String str : map.values()) {
    if ("b".equals(str)) {
        map.put(5, "f");
    }
}
System.out.println(map.get(5));

它将发生在ConcurrentModificationException。在这种情况下,我知道我们不能修改正在迭代的集合。

但是,请考虑以下代码。我只删除一行,即map.put(4,"e");

看起来不错!

代码语言:javascript
复制
Map<Integer,String> map = new HashMap<Integer, String> (5);
map.put(1, "a");
map.put(2, null);
map.put(3, "b");
for (String str : map.values()) {
    if ("b".equals(str)) {
        map.put(5, "f");
    }
}
System.out.println(map.get(5));

有小费吗?为什么会发生这种事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-07 15:55:20

"b“成为最后一个元素。

检查在迭代器的next方法中执行,不再被调用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39921250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档