In the Java development process encountered similar exception information Exception in thread "main" java.util.ConcurrentModificationException,
The following is a description of the cause of the exception and the improvement of the exception, the content is very simple, there are any problems to be corrected.
Suppose we want to implement an example of whether there is a "world" element in the set, and if so, add a "Java ee" element
The code for the exception appears as follows:
Import java.util.ArrayList;Import Java.util.Iterator;PublicClass Test {PublicStaticvoid Main (string[] args) {arraylist<string> array = new arraylist<string> (); //Create and add Element array.add ("Hello"); Array.add ("World"); Array.add ("Java"); Iterator it = array.iterator (); while (It.hasnext ()) { String s = (string) it.next (); if ("World". Equals (s)) { Array.add ("Java ee"); }}}
1. Exception explanation
2. Here are two ways to resolve this exception
Import java.util.ArrayList;PublicClass Test {PublicStaticvoid Main (String[] args) {arraylist<String>Array =New arraylist<String> ();Creating and adding elementsArray.add ("Hello");Array.add ("World");Array.add ("Java");Method 1: Iterator iteration element, iterator modification elementThe iterator iterator does not add functionality, so we use its sub-interface ListiteratorListiterator lit = Array.listiterator ();while (Lit.hasnext ()) {string s = (string) lit.next ();if ("World". Equals (s)) {Lit.add ("Java ee");// }// }System.out.println ("List1:" + array);Method 2: Set traversal element, set modify element (normal for)for (int x =0; X <Array.Size (); X + +) {string s = (string) array.get (x); if ( "World". Equals (s)) { "java ee");}} System.out. println ( "List2:" + array); //mode 3: Enhanced for loop //enhanced for Loop writes the same error because it is itself a substitute for the iterator's //for (String s:array) {//if ("World". Equals (s)) {//array.add (" Java ee "); //} //} //System.out.println ("LIST3:" + Array);}}
Java.util.ConcurrentModificationException's understanding and modification