请考虑以下代码。
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");
看起来不错!
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));有小费吗?为什么会发生这种事?
发布于 2016-10-07 15:55:20
"b“成为最后一个元素。
检查在迭代器的next方法中执行,不再被调用。
https://stackoverflow.com/questions/39921250
复制相似问题