hashmap迭代时不允许修改?
来源:9-10 结构图和特点

1jushi
2020-03-30
悟空老师,我测试迭代时可以修改呀
package collections.predecessor;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("a", 123);
System.out.println(hashMap.get("a"));
Iterator iter = hashMap.keySet().iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
hashMap.put(key, 666);
Integer value = hashMap.get(key);
System.out.println(hashMap.get(key));
}
}
}
写回答
1回答
-
1jushi
提问者
2020-03-30
看了后面讲的ArrayList迭代修改报错的解释大概明白了一些原理。但是发现上面代码在迭代过程进行修改时,put已有的key没报错,put新的key会报错,关于这点不明白,因为看HashMap的put方法源码,只要调用put,就会执行++modCount,也就是说只要put,那modCount != expectedModCount,肯定会报错。
hashMap.put("a", 123) //不报错 hashMap.put("newKey", 666) //报错
122020-03-30
相似问题