我有一個HashMap。我像這樣循環瀏覽地圖:在迭代過程中更改HashMap鍵/值是否安全?
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Long key : map.keySet()) {
int value = map.get(key);
value--;
map.put(key, value);
}
是我用來更新地圖安全的方式嗎?安全,因爲它不會因迭代而損壞地圖。
我有一個HashMap。我像這樣循環瀏覽地圖:在迭代過程中更改HashMap鍵/值是否安全?
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Long key : map.keySet()) {
int value = map.get(key);
value--;
map.put(key, value);
}
是我用來更新地圖安全的方式嗎?安全,因爲它不會因迭代而損壞地圖。
由於您只是更改Map中現有鍵的值,因此您正在執行此操作非常安全。
但是,如果您打算從Map中刪除條目,請記住使用Iterator。
正如您在HashMap source code中看到的,put
方法僅在提供新密鑰時修改modCount
。迭代器使用modCount
來檢查更改,如果在迭代器的兩次調用next()
之間發生這樣的更改,則會拋出ConcurrentModificationException
。這意味着您使用put
的方式是安全。
你可以考慮更高效地編寫代碼:
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Entry<Long, Integer> entry : map.entrySet()) {
entry.setValue(entry.getValue() - 1);
}
這是一個微型的優化,但有時它很重要,你也不會失去任何東西。它更短,清除任何關於啓動安全性的含糊不清!
這是太多的代碼,我不知道,但我覺得它很醜陋:/ –