A Concurrentmodificationexception exception was encountered while learning the Java set iterator traversing the contents of the collection and adding content.
For (iterator<string> it=arrlist.iterator (); It.hasnext ();) {
//system.out.println (It.next ()); When the For loop ends, the It reference is recycled by the collector pattern
p=pattern.compile ("Wind Qingyang");
Matcher M=p.matcher (It.next ());
if (M.matches ()) {
arrlist.add ("White Snake");
}
An exception has occurred, query the Add () method Source:
Ensurecapacityinternal (size + 1); Increments modcount!!
elementdata[size++] = e;
return true;
Here makes Modcount's plus one
Then I look at the source of the next () method:
Public E Next () {
checkforcomodification ();
int i = cursor;
if (i >= size)
throw new Nosuchelementexception ();
object[] Elementdata = ArrayList.this.elementData;
if (i >= elementdata.length)
throw new Concurrentmodificationexception ();
cursor = i + 1;
Return (E) Elementdata[lastret = i];
}
See it call a Checkforcomodification () method, view its source code:
final void Checkforcomodification () {
if (modcount!= expectedmodcount)//focus here. Here because the value of the Modcount is added 1, so it is not equal, so it will be an error,
//This is to prevent the iteration is not completed when the iterator depends on the set to modify.
throw new Concurrentmodificationexception ();
}
The meaning of this code is to compare the values of Modcount and Expectedmodcount, and if the value is different, throw the Concurrentmodificationexception () exception that was encountered before.
In summary, when we call Add () method is, make Modcount value plus one, this time and Expectemodcount value is not the same, so the error. Think again, this is worth the action is to prevent you in
When traversing the collection, the collection is added or deleted, but the iterator is unaware. We know that the iterator is dependent on the collection, which obviously does not fit the original design, so it is not surprising that the appearance of the anomaly
Solution:
First, the break () method, which iterates over the qualifying content, jumps out of the iteration.
Second, the use of iterators to add or remove features, the list only remove () method can delete content, to add content, you must use the ArrayList-specific iterator-listiterator in the Add () method.
Use a For loop to traverse an array based on index