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.
ConcurrentModificationException.Iterator for HashMap will trigger a concurrent modification exception even if you do remove or put in the same thread. If you use ConcurrentHashMap it will not produce a ConcurrentModificationException as its designed not to.put().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