suppose you have a HashMap m
and there is already a key value pair <"key1", object>
inside.
can you do the following?
m.put("newkey", m.remove("key1"))
will you get a ConcurrentModificationException
?
suppose you have a HashMap m
and there is already a key value pair <"key1", object>
inside.
can you do the following?
m.put("newkey", m.remove("key1"))
will you get a ConcurrentModificationException
?
You can do that as long as it's not in the body of a loop that is iterating over the hashMap entries. The way that will work is that the remove operation will execute and complete before the put operation so it's semantically equivalent to doing it in 2 lines.
Just tested it for you.
Map<String, Object> map = new HashMap<String, Object>();
map.put("k1", Integer.valueOf(999));
map.put("k2", map.remove("k1"));
System.out.println(map.get("k2"));
Prints:
999
No exception (ConcurrentModificationException
).
Since m.remove
returns the object previously associated with that key, you should be able to use that object however you like. So no, I don't believe you should get an exception.
They are actually not fired simultaneously. The remove is called first, and done with, then the get is called, so I see no reason as to why there would be an exception.
See this if you need to modify when looping: Iterate through a HashMap