Search code examples
javaarraylisthashmapconcurrentmodification

avoiding concurrent modification exception with Map<Long,List<POJO>>


I have the data structure Map<Long,List<POJO>>. I need to iterate over the map and for each List, I need to add elements to the list. So for instance, if a list had 10 elements, it may end up with 12. My question: will there cause a concurrent modification exception if I take a simple approach of iterating the map and modify each List<POJO>? Since I won't be explicitly changing the address of each List. I guess a sub-question is, will the List change its address if it needs a larger continuous block to hold its array.


Solution

  • The answer to both of your questions are "no":

    • There will be no ConcurrentModificationException if all you're doing is mutating the values of the map, since you're not actually changing the values themselves, just changing their state. This is easy enough to test and confirm for yourself.

    • A list will not "change its address" if you try to add more elements than it can hold. Instead, more room will be allocated internally. For an ArrayList, for example, the internal array will be replaced by a new, larger array and the elements will be copied over.