ImportJava.util.ArrayList;ImportJava.util.List;ImportJava.util.ListIterator;/**Problem * There is a set, as below, I would like to judge there is no "world" this element, if there is, I will add a "Java ee" element, please write code implementation. * * Concurrentmodificationexception: But the method detects concurrent modifications to the object, but does not allow this exception to be thrown when this modification is allowed. * Cause: * Due to the constant addition of new elements in the process of traversal, iterators are dependent on the collection and exist, after the success of the judgment, the collection of new elements, and the iterator does not know, so the error, this error is called concurrency modification exception. * This is actually a description of the problem: when an iterator iterates through an element, the element cannot be modified by the collection. * * How to solve it? * A: Iterator iteration element, iterator modifying element * element followed by the amount element of the iteration just after the * B: Set traversal element, set modify element (normal for) * element last added * **/PublicClassListIteratorDemo2 {PublicStaticvoidMain (string[] args) {List list=NewArrayList (); List.add ("Hello"); List.add ("World"); List.add ("Java");//The wrong way: the iterator iterates over the elements, the collection modifies the elements, the iterator does not know the changes to the collection, and throws a concurrency modification exception.//Iterator It=list.iterator ();//while (It.hasnext ()) {//String s= (String) it.next ();//if ("World". Equals (s)) {//List.add ("Java ee");//}//}//Right way one: iterator iteration element, iterator modification element//Listiterator Lit=list.listiterator ();//while (Lit.hasnext ()) {// string s= (string) lit.next (); // if ("World". Equals (s)) { // Lit.add ("Java ee"); }// // right way two: Set traversal element, set modify element (normal for) for (int i=0;i<list.size (); I++) {String S= (String) List.get (i); if ("World" .equals (s)) {list.add ("Java ee" ); }} System.out.println ("list:" +list);}
Concurrentmodificationexception Collection Concurrency modification exception resolution