Im trying to delete item from a ArrayList
. Some times it pops an exception, java.util.ConcurrentModificationException
.
First I tried to remove them by array_list_name.remove(i)
, but it failed and some people were asked to use Iterator instead. So my current code is as follows:
for (Iterator<Collectable> iter = array_list_name.iterator(); iter.hasNext();) {
Collectable s = iter.next();
if (s.equals(array_list_name.get(id))){
iter.remove();
return true;
}
}
And I call array_list_name
inside onDraw()
function in view. My view is a SurfaceView
. Can anyone suggest me how to delete items from ArrayList
without getting this error?
iter.remove()
and see CME, not always but sometimes?onDraw
is called in the UI thread so it might be invoked at the same time as item removal in the other thread.The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress...