Document directory
- [Introduction]
- [Confused]
[Introduction]
When iterations of a set element, you often want to modify the Set (Add/Remove), similar to the following code:
for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) { Integer val = it.next(); if (val == 5) { list.remove(val); }}
Running this code throws an exception in Java. util. concurrentmodificationexception.
[Confused]
(Explained in arraylist) in arraylist, its modification operations (Add/Remove) will add 1 to the modcount field. modcount can be considered as a version number, each time the element in the set is modified, it will be + 1 (even if it overflows ). Next, let's take a look at the iteraor method in absrtactlist.
public Iterator<E> iterator() { return new Itr();}
It returns an internal class that implements the iterator interface. The Code is as follows:
Private class itr implements iterator <E> {int cursor = 0; int lastret =-1; int expectedmodcount = modcount; Public Boolean hasnext () {return cursor! = Size () ;}public e next () {checkforcomodification (); try {e next = get (cursor); lastret = cursor ++; return next ;} catch (indexoutofboundsexception e) {checkforcomodification (); throw new nosuchelementexception () ;}} public void remove () {If (lastret =-1) throw new illegalstateexception (); checkforcomodification (); try {policactlist. this. remove (lastret); If (lastret <cursor) cursor --; la Stret =-1; // modify the value of expectedmodcount = modcount;} catch (distinct E) {Throw new concurrentmodificationexception () ;}} final void checkforcomodification () {If (modcount! = Expectedmodcount) throw new concurrentmodificationexception ();}}
In the internal itr class, there is an expectedmodcount field, which is equal to modcount during initialization. That is, when we call list. iterator () to return the iterator, this field is initialized to be equal to modcount. In the itr class, the next/remove Methods call the checkforcomodification () method. In this method, modcount = expectedmodcount is detected. If not, concurrentmodificationexception is thrown.
As mentioned above, in the Add/Remove operation of the Set, modcount is added to + 1.
Let's take a look at the code that was just introduced. In the iteration process, execute list. remove (VAL), so that modcount + 1, the current cycle, execute it. next (), checkforcomodification method found modcount! = Expectedmodcount, an exception is thrown.
[Solution]
What if I want to delete elements during iteration?
Let's take a look at the remove () method of the internal itr class. After deleting an element, there is such an expectedmodcount = modcount statement to synchronously modify the value of expectedmodcount. Therefore, if you need to delete elements when using the iterator iteration, you can use the remove method provided by the iterator. The add operation is not allowed throughout the iterator iteration process. Other sets (MAP/set) use the same iterator for iteration.