Concurrent Modification Exception : adding to an ArrayList

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

    The accepted solution (to create a copy of the collection) usually works well.

    However, if the Element contains another collection this does not make a deep copy!

    Example:

    class Element {
       List kids;
    
       getKids() {
          return kids;
       }
    }
    

    Now when you create a copy of the List of Elements:

    for (Element element : new ArrayList(elements)) { ... }
    

    You can still get a ConcurrentModificationException if you iterate over element.getKids() and, parally, alter the kids of that element.

    Looking back it's obvious, but I ended up in this thread so maybe this hint helps others, too:

    class Element {
       List kids;
    
       getKids() {
          // Return a copy of the child collection
          return new ArrayList(kids);
       }
    }
    

提交回复
热议问题