Causes and solutions of concurrency modification exceptions
* A: Case Presentation
* Requirements: I have a collection, ask, I want to judge there is no "world" this element, if there is, I will add a "Java ee" element, please write code implementation.
List List = new ArrayList ();
List.add ("a");
List.add ("B");
List.add ("World");
List.add ("D");
List.add ("E");
/*iterator it = List.iterator (); //EDGE traversal, Edge add element--------is an operation not allowed by the program
while (It.hasnext ()) {
String str = (string) it.next ();
if (Str.equals ("World")) {
List.add ("Java ee");//This throws Concurrentmodificationexception concurrency modification exception
}
}*/
* B:concurrentmodificationexception appears
* Iterator traversal, collection modification collection
* C: Solution
* A: Iterator iteration element, iterator modification element (Listiterator unique function Add)//listiterator unique method to solve this problem
* B: Set traversal element, set modify element
Workaround:
Listiterator lit = List.listiterator (); //If you want to add elements during traversal, you can use the Add method in Listiterator
while (Lit.hasnext ()) {
String str = (string) lit.next ();
if (Str.equals ("World")) {
Lit.add ("Java ee");
List.add ("Java ee");
}
}
Listiterator
* Boolean hasnext () whether there is a next
* Boolean hasprevious () whether there is a previous
* Object Next () returns the next element
* Object Previous (); Returns the previous element
Java Listiterator Interface