Reputation: 6372
I have a HashMap. I loop through the map like this:
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Long key : map.keySet() ) {
int value = map.get(key);
value--;
map.put(key, value);
}
Is the way I'm using to update the map safe? Safe in the sense that it doesn't damage the map because of the iteration.
Upvotes: 9
Views: 10249
Reputation: 5619
As you can see in the HashMap source code, the put
method only modifies the modCount
when a new key is provided. modCount
is used by the iterator to check for changes, and if such a change occurred between two calls to an iterator's next()
, a ConcurrentModificationException
would be thrown. This means that the way you are using put
is safe.
Upvotes: 9
Reputation: 38526
You could consider writing your code more efficiently as:
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Entry<Long, Integer> entry : map.entrySet() ) {
entry.setValue(entry.getValue() - 1);
}
This is a micro-optimization, but sometimes it matters, and you don't lose anything. It's shorter and clears up any ambiguity about the safety to boot!
Upvotes: 9
Reputation: 785128
It is perfectly safe operation that you're doing since you're just changing value of an existing key in the Map.
However if you are ever going to delete an entry from Map then remeber to use Iterator.
Upvotes: 3