If you modify the List object when you use Iterator to iterate over the List object, a java. util. ConcurrentModificationException exception is reported. The following is an example:
List<String> list = ArrayList<String> list.add("a" list.add("b" list.add("c" list.add("d" list.add("e" Iterator iterator = String str = (str.equals("c" } }
Result:
"main"81979120)
When the list iterator () method is called, an Itr object (implementing the Iterator Interface) is returned ):
Iterator<E> }
Let's take a look at the Itr class:
Itr Iterator<E> cursor; lastRet = -1; expectedModCount = modCount; cursor != @SuppressWarnings("unchecked" checkForComodification(); i = (i >= Object[] elementData = ArrayList. (i >= cursor = i + 1 (E) elementData[lastRet = (lastRet < 0 ArrayList. cursor = lastRet = -1 expectedModCount = } (modCount != }
The List object has a member variable modCount, which indicates the number of times the List object was modified. Every time the List object is modified, modCount adds 1.
In the Itr class, there is a member variable expectedModCount whose value is the modCount value of the List when an Itr object is created. This variable is used to check whether the List object has been modified during iteration. If so, a java. util. ConcurrentModificationException exception is thrown. Each time you call the next () method of an Itr object, a method is called for verification,
Method. In this case, an exception is thrown.
cursor != }
It uses the cursor value of the Itr object and the size value of the List object to determine whether there are still non-iterative objects. When "d" is traversed, cursor = 4, when "d" is deleted, the size of the List object is reduced by 1, and the size is 5 first, and then 4. At this time, the cursor and size are equal, hasNext () if the returned value is false, the traversal is over. Therefore, if the next () method is not executed after deletion, no exception is thrown. Of course, "e" is not output.
To avoid this exception, we can use CopyOnWriteArrayList to replace ArrayList. CopyOnWriteArrayList supports concurrent access, so there is no problem in simultaneous iteration and modification.