ConcurrentModificationException: An error occurred while modifying the concurrency,
Requirement: I have a set, as shown below. Could you tell me if there is any "world" element in it? If so, I will add a "javaee" element. Please write the code for implementation.
Import java. util. ArrayList;
Import java. util. Iterator;
Import java. util. List;
Public class Demo {
Public static void main (String [] args ){
List <String> list = new ArrayList <String> ();
List. add ("hello ");
List. add ("world ");
List. add ("java ");
Iterator <String> it = list. iterator ();
While (it. hasNext ()){
String s = it. next ();
If ("world". equals (s )){
List. add ("javaee ");
}
}
System. out. println ("list:" + list );
}
}
The above code will encounter ConcurrentModificationException during runtime: concurrent modification exception
Cause:
The iterator is dependent on the set. After successful judgment, an element is added to the set center, but the iterator does not know, so an error is returned. This error is called a concurrent modification exception.
In fact, this problem is described as follows: when the iterator traverses elements, the elements cannot be modified through the set.
So how should we solve this problem?
Method 1: We can use the iterator to iterate elements and the iterator to add elements.
In this case, the ListIterator listIterator () List iterator exclusive to the List set is used.
This Iterator inherits the Iterator, so you can directly use the hasNext () and next () methods.
In addition, the void add (Object obj) method of ListIterator can add elements.
Note: The elements added by ListIterator follow the elements of the previous iteration.
The code for completing the above requirements using the list iterator is as follows:
Import java. util. ArrayList;
Import java. util. List;
Import java. util. ListIterator;
Public class Demo {
Public static void main (String [] args ){
List <String> list = new ArrayList <String> ();
List. add ("hello ");
List. add ("world ");
List. add ("java ");
ListIterator <String> separator = list. listIterator ();
While (iterator. hasNext ()){
String s = values. next ();
If ("world". equals (s )){
Examples. add ("javaee ");
}
}
System. out. println ("list:" + list );
}
}
Method 2: Use a set to traverse elements and a set to modify elements (use common)
Use the size () and get () Methods of the List set to traverse the set.
Note that when you use common for to traverse and modify the set elements, the elements are added at the end.
The code for using common for to complete the preceding requirements is as follows:
Import java. util. ArrayList;
Import java. util. List;
Public class Demo {
Public static void main (String [] args ){
List <String> list = new ArrayList <String> ();
List. add ("hello ");
List. add ("world ");
List. add ("java ");
For (int x = 0; x <list. size (); x ++ ){
String s = list. get (x );
If ("world". equals (s )){
List. add ("javaee ");
}
}
System. out. println ("list:" + list );
}
}