Concurrent Modification Exception : adding to an ArrayList

前端 未结 10 905
醉梦人生
醉梦人生 2020-11-22 10:53

The problem occurs at

Element element = it.next();

And this code which contains that line, is inside of an OnTouchEvent

10条回答
  •  名媛妹妹
    2020-11-22 11:20

    You're not allowed to add an entry to a collection while you're iterating over it.

    One option is to create a new List for new entries while you're iterating over mElements, and then add all the new ones to mElement afterwards (mElements.addAll(newElements)). Of course, that means you won't have executed the loop body for those new elements - is that a problem?

    At the same time, I'd recommend that you update your code to use the enhanced for loop:

    for (Element element : mElements) {
        ...
    }
    

提交回复
热议问题