我有一个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。我按照以下方式循环遍历它:
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Long key : map.keySet() ) {
int value = map.get(key);
value--;
map.put(key, value);
}
我正在使用的更新地图的方式安全吗?这里所说的安全是指在迭代过程中不会损坏地图。
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Entry<Long, Integer> entry : map.entrySet() ) {
entry.setValue(entry.getValue() - 1);
}
这是一种微小的优化,但有时很重要,而且你不会失去任何东西。它更加简洁明了,还能消除任何关于安全性的歧义!
正如您在HashMap源代码中可以看到的那样,当提供一个新的键时,put
方法只会修改modCount
。迭代器使用modCount
检查是否有更改,如果在两次调用迭代器的next()
之间发生了更改,则会抛出ConcurrentModificationException
异常。这意味着您使用put
的方式是安全的。
您正在进行的操作是完全安全的,因为您只是更改了Map中现有键的值。
但是,如果您曾经想要从Map中删除一个条目,请记得使用迭代器。