Java - adding elements to list while iterating over it

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

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

5条回答
  •  渐次进展
    2020-12-10 01:50

    Instead of using an iterator, you can use a for loop with an index. For example:

    int originalLength = list.length();
    for (int i = 0; i < originalLength; i++) {
      MyType mt = list.get(i);
      //... processing
      //... insertions
    }
    

提交回复
热议问题