简体   繁体   English

避免Map发生并发修改异常 <Long,List<POJO> &gt;

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

I have the data structure Map<Long,List<POJO>> . 我有数据结构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> ? 因此,例如,如果一个列表包含10个元素,则可能以12结尾。我的问题:如果我采用一种简单的方法来迭代映射并修改每个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. 我猜有一个子问题,如果列表需要更大的连续块来保存其数组,列表是否会更改其地址。

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. 如果您所做的全部就是更改地图的值,则不会出现ConcurrentModificationException ,因为您实际上没有更改值本身,而只是更改了它们的状态。 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. 例如,对于ArrayList ,内部数组将被一个更大的新数组替换,并且元素将被复制。

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. 如果您尝试在迭代时修改/添加到地图,则会出现Exception,但是在您的情况下,您正在迭代地图,但是将其添加到Map内的List中,因此不会有问题。 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. 关于第二个问题,Address永远不会更改,而是取决于实现,例如,如果它是ArrayList,并且在同一位置没有可用的附加空间,则将创建新的List并复制元素,但是并非总是如此。

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. ArrayList以其初始容量创建,一旦达到限制,则增加一倍。 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. 链表为节点分配空间,下一个引用被保留并保留为对象的属性,因此不需要连续的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM