The problem occurs at
Element element = it.next();
And this code which contains that line, is inside of an OnTouchEvent
You could use an auto-decrement for
loop, and deal with the additional elements next time.
List additionalElements = new ArrayList();
for(int i = mElements.size() - 1; i > -1 ; i--){
//your business
additionalElements.add(newElement);
}
mElements.add(additionalElements);
ConcurrentModificationException occurs when you modify the list (by adding or removing elements) while traversing a list with Iterator
.
Try
List<Element> thingsToBeAdd = new ArrayList<Element>();
for(Iterator<Element> 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.
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<Element>
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) {
...
}
Well i have tried all the aspects in my case where i was iterating in an adapter a list but due to hitting again and again i showed me the message of exception being thrown . I tried Casting the list to
= (CopyOnWriteArraylist<MyClass>)mylist.value;
but it also throwed me an exception of CouldNotCastException,(and i finally pondered over the fact that why do they use or provide us a facality of casting).
I even used the so called Synchronized Block too, but even it didn't worked or i might would have been using it in a wrong way.
Thus it's all when i finally used the #all of time# Technique of handling the exception in try catch block, and it worked So put your code in the
try{
//block
}catch(ConcurrentModificationException){
//thus handling my code over here
}
I solved creating a lock (Kotlin):
import java.util.concurrent.locks.ReentrantLock
Class A {
private val listLock = ReentrantLock()
fun doSomething(newElement){
listLock.lock()
list.add(newElement)
listLock.unlock()
}
}
An indexed for loop should also work.
for (int i = 0; i < collection.size(); i++)