I have objects Bullet that I add to two ArrayLists at once, the lists are briefly described below. After certain operations are done I wish to remove a bullet from both lists. Is this approach correct? I keep on getting an error: java.util.ConcurrentModificationException
Alternatively, can you think of a better solution than ArrayList for the purpose of handling objects in this manner?
//there are ArrayList<Bullet> bullets and ArrayList<Updatable> updatable, in the class
public void removeBullet(Bullet bullet) {
for (ListIterator<Bullet> bulletIterator = bullets.listIterator(); bulletIterator.hasNext();) {
Bullet tempBullet = bulletIterator.next();
if (tempBullet.equals(bullet)) {
for (ListIterator<Updatable> updatableIterator = updatable.listIterator(); updatableIterator.hasNext();) {
Updatable tempUpdatable = updatableIterator.next();
if (tempUpdatable.equals(bullet)) {
updatableIterator.remove();
bulletIterator.remove();
return;
}
}
}
}
}
EDIT: The source of problem was that I used an iterator on one of the lists, at exact same time in a different place, hence the error. This code worked fine for the updatable list.