Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent Modification Exception in Java [duplicate]

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.

like image 210
muneikh Avatar asked Dec 16 '25 23:12

muneikh


1 Answers

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.

like image 60
Rohit Jain Avatar answered Dec 19 '25 12:12

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!