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
