Concurrent Modification Exception : adding to an ArrayList

前端 未结 10 997
醉梦人生
醉梦人生 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:18

    ConcurrentModificationException occurs when you modify the list (by adding or removing elements) while traversing a list with Iterator.

    Try

    List thingsToBeAdd = new ArrayList();
    for(Iterator it = mElements.iterator(); it.hasNext();) {
        Element element = it.next();
        if(...) {  
            //irrelevant stuff..
            if(element.cFlag){
                // mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
                thingsToBeAdd.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
                element.cFlag = false;
            }           
        }
    }
    mElements.addAll(thingsToBeAdd );
    

    Also you should consider enhanced for each loop as Jon suggested.

提交回复
热议问题