Note: Reference blog: https://www.cnblogs.com/dolphin0520/p/3933551.html
1. Abnormal recurrence in single-thread environment
public static void Main (string[] args) { arraylist<integer> list = new arraylist<integer> (); List.add (2); iterator<integer> Iterator = List.iterator (); while (Iterator.hasnext ()) { integer integer = Iterator.next (); if (integer==2) { list.remove (integer); Iterator.remove (); Correct notation }}}
When the while (Iterator.hasnext ()) loop is traversed, only the last element of the ArrayList internal elementdata[] is allowed to be deleted, but not removed from the middle.
In the source code of Iterator.next (), the method is executed first: Checkforcomodification (); This method:
final void Checkforcomodification () { if (modcount! = expectedmodcount) throw new Concurrentmodificationexception (); }
Only if the values of the two variables are equal do not error. and List.add (2) operation and List.remove (integer); Operation will make modcount++; But the variable expectedmodcount is the variable of the ITR subclass of the inner class, the instantiation method of the subclass is: List.iterator (); An instance object is assigned an initial value:
int expectedmodcount = Modcount; Therefore, it is not allowed to have List.add (2) operation and List.remove (integer) within the while (Iterator.hasnext ()) loop method, or it will cause expectedmodcount! = Modcount, which in turn leads to the throw of the new Concurrentmodificationexception ();
Exception in Thread "Thread-1" Java.util.ConcurrentModificationException exception causes and workarounds