I am getting the ConcurrentModificationException while executing this code. I am unable to figure out why it is happening?
private void verifyBookingIfAvailable(ArrayList<Integer> list, int id) {
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
int value = iterator.next();
if (value == id) {
int index = list.indexOf(id);
if (index != -1) {
list.remove(index);
}
}
}
}
Thanks in advance.
You are removing the element in the list using the list
reference itself, which can throw ConcurrentModificationException
. Note that, this might work sometimes, but not always, and is not guaranteed to work perfectly.
Also, even though you use Iterator
to iterate your list, you still shouldn't use list.remove
, you should only use iterator.remove()
to remove the elements, else it won't make any difference, whether you use iterators or enhanced for-loop.
So, use iterator.remove()
to remove elements.
if (index != -1) {
iterator.remove(value);
}
See this post: - java-efficient-equivalent-to-removing-while-iterating-a-collection for more detailed explanation.