How to avoid ConcurrentModificationException when iterating over a map and changing values?

前端 未结 7 1019
眼角桃花
眼角桃花 2020-12-06 09:46

I\'ve got a map containing some keys (Strings) and values (POJOs)

I want to iterate through this map and alter some of the data in the POJO.

The current code

7条回答
  •  一整个雨季
    2020-12-06 10:25

    Another approach, somewhat tortured, is to use java.util.concurrent.atomic.AtomicReference as your map's value type. In your case, that would mean declaring your map of type

    Map>
    

    You certainly don't need the atomic nature of the reference, but it's a cheap way to make the value slots rebindable without having to replace the entire Map.Entry via Map#put().

    Still, having read some of the other responses here, I too recommend use of Map.Entry#setValue(), which I had never needed nor noticed until today.

提交回复
热议问题