Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to change a HashMap key/value during iteration?

Tags:

java

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.

like image 668
Jack Twain Avatar asked Jul 16 '13 21:07

Jack Twain


1 Answers

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!

like image 146
Steven Schlansker Avatar answered Nov 15 '22 18:11

Steven Schlansker