* method() to avoid ConcurrentModificationExcetpion. * make sure you use Iterator's remove() method or not ArrayList's remove() * If you want to remove elements while traversing list then * one thread is modifying the collection e.g. * Unlike the name suggests, this error can come even if only * Java Program to demonstrate how to deal with In this example, we are looping over ArrayList using advanced for loop and removing selected elements, but because we are using ArrayList's remove() method. Here is the Java program to demonstrate one scenario where you get the ConcurrentModificationException even if just one thread is modifying the ArrayList. Solving ConcurrentModificationException while Iterating over ArrayList in Java Solution: Use Iterator if you are doing it on the single-threaded environment, otherwise use concurrent collection classes like CopyOnWriteArrayList to remove elements while you are looping over it. Now if you check this checkForComodification() method, you will find what I just said: Throw new ConcurrentModificationException() Here is the code snippet from the hasNext() method which shows there is check for modCount: If you modify the collection by adding or removing elements then modCount will change and it will not match with the expected modCount, hence Iterator will throw ConcurrentModificationException. When you are iterating over ArrayList then Iterator's next() method keep track of modCount. Problem: loop over an ArrayList and remove selected elements, but remove() is throwing " Exception in thread "main" ".Ĭause: The real cause of ConcurrentModfiicationException is inconsistent modCount. Other methods of List which structurally modify List also use this method like add(), remove(). A confirmation email will be sent to your email address.Both Iterator and ListIterator use this field to detect unexpected change.Click on "Continue" to confirm your purchase.The ConcurrentModificationException is used to fail-fast when something being iterated on is modified. Choose the payment method, and then enter your credit card details. The ConcurrentModificationException is a very common exception in Java that occurs usually while working with Collections.Check the "I agree to the terms and conditions" box, and then click on "Continue". ![]()
0 Comments
Leave a Reply. |