在这种情况下如何避免ConcurrentModificationException?

时间:2019-10-22 06:04:56

标签: java list for-loop concurrentmodification

我了解到,当我尝试修改(在这种情况下添加)列表时,我收到了ConcurrentModificationException,但是解决此问题的最佳解决方案是什么?

for (Map.Entry<String, Child> entry : children.entrySet() {
     childEvent.child = entry.getValue();
     if (childEvent.getDate() != null && childEvent.getDate().equals(selectedDate)) {
         if(this.selectedDayevents.isEmpty()) {
             // List                                
             this.selectedDayevents.add(childEvent);
          }
         for (CareDay selectedCareDay : this.selectedDayevents) {
             // Here I have to combine data in some cases...
         }
     }  
}

2 个答案:

答案 0 :(得分:0)

解决此问题的一种简单方法是遍历条目集的副本

for (Map.Entry<String, Child> entry : new HashSet<>(children.entrySet())) {
    // same code
}

如果您的地图不太大并且不经常使用,则不会发现效果有所不同。

答案 1 :(得分:-1)

如果您要求启用对集合的并发访问,则应探索Java并发API,尤其是针对ConcurrentHashMapConcurrentSkipListMap的情况。