package ee;
import java.util.HashMap;
import java.util.Iterator;
public class Demo {
public static void main(String[] args) {
HashMap<Integer, Integer> count = new HashMap<Integer, Integer>();
count.put(1,11);
count.put(2,22);
count.put(3,33);
//错误的 会抛出异常 ----ConcurrentModificationException
/* for (Integer i : count.keySet()) {
if(i == 2){
count.remove(i);
}
System.out.println(i);
}*/
//正确的 it.remove(); // 这个可以实现 遍历的过程中删除某个元素
Iterator<Integer> it = count.keySet().iterator();
while(it.hasNext()) {
Integer key = it.next();
if(key == 2){
it.remove(); // 这个可以实现 遍历的过程中删除某个元素
}
if(key == 3){
count.put(key, 44);
}
}
for (Integer value : count.values()) {
System.out.println(value);
}
}
}
参考文档:
https://www.cnblogs.com/cherish010/p/9178085.html
https://blog.csdn.net/u011517841/article/details/82955498
原文:https://www.cnblogs.com/william-dai/p/15064368.html