Java - adding elements to list while iterating over it

前端 未结 5 1777
花落未央
花落未央 2020-12-10 00:53

I want to avoid getting ConcurrentModificationException. How would I do it?

5条回答
  •  [愿得一人]
    2020-12-10 01:46

    There are three approaches to avoid above exception

    1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.

    2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading.

    3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.

提交回复
热议问题