I have a LinkedList of objects im trying to iterate over(using an iterator), see if they have any collision, if so, remove it from the list. However, I am getting a concurrent modification exception. I put it in a synchronized block, and I also tried catching the error in a try catch block, neither seem to help at all, the code is here:
private void updateTP() {
synchronized (toiletpaper) {
Iterator<ToiletPaper> iter = toiletpaper.iterator();
while (iter.hasNext()) {
ToiletPaper tp = iter.next();
tp.update(1000, 700);
if (toilet.overlaps(tp)) {
System.out.println("tp splash!");
toiletpaper.remove(tp);
menu.removeLife();
}
}
}
}
Any thoughts on the problem would be appreciated, I looked through here and google, and all of them said either catch the exception or synchronize it, which neither seem to work so… please help.
To avoid the exception, use
iter.remove()instead. This will remove the element via the iterator instance, rather than the current call, which searches and removes from the list separately – that is, a concurrent modification.