Concurrent modification exception in Java

See English answers > repeating through a collection, avoiding concurrent modificationexception when removing objects in a loop 23

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);
                    }
                }
        }
    }

Thank you in advance

Solution

You are using the list reference itself to delete elements in the list, which may throw a concurrentmodificationexception Please note that this may work sometimes, but not always, and there is no guarantee of perfect operation

In addition, even if you iterate over the list using iterator, you should still not use list Remove, you should only use iterator Remove () to remove the element, otherwise it will make no difference, whether you use an iterator or an enhanced for loop

Therefore, use iterator Remove() deletes the element

if (index != -1) {
    iterator.remove(value);
}

For detailed instructions, please refer to this post: – java-effective-equivalent-to-removing-while-iterating-a-collection

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>