Question

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.

Was it helpful?

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.

OTHER TIPS

If you try to modify/add to map while iterating over it, Exception will come, but in your case you are iterating over map but adding to List inside map, so there wont be a problem. about second question, Address is never changed but depends on implementation, say if it is ArrayList, and on addition space is not available at same place, then new List is created and elements copied, this is not the case always though.

This list will change it's size and memory location if it needs to. ArrayLists are created with their initial capacity and then doubled once the limit is reached. If there is not consecutive memory, the address will be changed to a different continuous block to hold the list. However, a linked list doesn't allocate in this way. A linked list allocates space for a node and next references are maintained and kept as an attribute of the object so continuous memory isn't necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top