When Java iterates through the list, it throws an concurrentmodificationexception exception if the element is removed.
The exception is that when we iterate over elements, we remove the elements from the list collection at the same time.
It's no problem when we write code like this.
list<string> list = new arraylist<> ();
* *
/List.add ("AAA");
String value = null;
for (int i = 0; i < list.size (); i++) {
value = List.get (i);
List.remove (value);
}
However, when we write in this way, there is a problem.
/* Throw concurrentmodificationexception
list.add ("AAA");
String value = null;
for (iterator<string> iterator = List.iterator (); Iterator.hasnext ();) {
value = Iterator.next ();
List.remove (value);
}
* * *
throw concurrentmodificationexception
list.add ("AAA");
for (string string:list) {
list.remove (string);
}
* * *
throw concurrentmodificationexception
list.add ("AAA");
List.foreach (s-> {
list.remove (s);
});
*/
The following report Concurrentmodificationexception exception is written because of the use of iterators to write.
This exception is not reported when we use the ArrayList subscript to visit.
Of course, it's OK to use iterators if you must. Use the method provided by the iterator for the remove operation.
List.add ("AAA");
String value = null;
for (iterator<string> iterator = List.iterator (); Iterator.hasnext ();) {
value = Iterator.next ();
Iterator.remove (); Use the Remove method provided by the iterator
}
The above method is used in a single thread, in the context of multithreading can be considered with copyonwritearraylist