Why concurrentmodificationexception arraylist




















Then begins the hunting, they spent countless hours to find the code which has the probability of concurrent modification. While in reality, ConcurrentModficationException can also come in a single-threaded environment.

To give you an example, just loop over a list using for loop and try to remove one element, you will get the ConcurrentModificatoinExcetpion? How does Java know to throw ConcurrentModificationExeption?

It uses a transient variable called modCount , which keeps track of how many times a list is modified structurally. Structural modifications are those that change the size of the list, which may affect the progress of iteration and may yield incorrect results. Both Iterator and ListIterator use this field to detect unexpected change. Other methods of List which structurally modify List also use this method e. Problem: loop over an ArrayList and remove selected elements, but remove is throwing " Exception in thread "main" java.

When you are iterating over ArrayList then Iterator's next method keep track of 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.

Konrad Garus Konrad Garus HugoGresse Yes, but this is the opposite direction. Iterator exposes remove that is safe for its iteration, something that foreach "loses".

Edward Dale Edward Dale I had a same problem with HashMap, fixed with another implemention of Map interface. You should test it yourself. Suganthan Madhavan Pillai Suganthan Madhavan Pillai 4, 7 7 gold badges 39 39 silver badges 74 74 bronze badges. The Overflow Blog. Does ES6 make JavaScript frameworks obsolete? Podcast Do polyglots have an edge when it comes to mastering programming Featured on Meta. Now live: A fully responsive profile. Linked See more linked questions. May 4, at pm.

V J reddy says:. October 8, at pm. Suma Gopalakrishna says:. July 22, at pm. April 14, at am. June 9, at pm.

Thibault says:. September 24, at am. Tran Nam Long says:. May 14, at am. March 26, at pm. February 4, at am. Binh Thanh Nguyen says:. January 12, at pm. Vivek says:. August 27, at am. Tiru says:. August 7, at am. Rob says:. July 23, at am.

RaviKant Gaur says:. June 28, at am. SwethaHarshini says:. April 27, at am. Myrna says:. February 1, at am. February 2, at am. November 26, at pm.

Ashish says:. July 2, at am. October 17, at am. October 17, at pm. Siavash says:. September 26, at am. July 18, at am. Ed says:. May 29, at am. May 29, at pm. Leave a Reply Cancel reply Your email address will not be published.

Leave this field empty. Exact matches only. Search in title. Search in content.



0コメント

  • 1000 / 1000