Deleting content directly in the map throws a Java.util.ConcurrentModificationException exception if you want to delete the iterator remove () method.
The following code complains:
Java code map<string,string> MAP = new hashmap<string,string> (); Map.put ("1", "a"); Map.put ("2", "B"); Map.put ("3", "C"); Iterator iterator = Map.keyset (). iterator (); while (Iterator.hasnext ()) {string key = (String) iterator.next (); if ("1". Equals (key) | | "2". Equals (Key)) {Map.Remove (key); } }
map<string,string> map = new hashmap<string,string> ();
Map.put ("1", "a");
Map.put ("2", "B");
Map.put ("3", "C");
Iterator iterator = Map.keyset (). iterator ();
while (Iterator.hasnext ()) {
string key = (String) iterator.next ();
if ("1". Equals (key) | | "2". Equals (Key)) {
map.remove (key);
}
}
The correct code is as follows:
Java code map<string,string> map = new hashmap<string,string> (); map.put ("1", "a"); Map.put ("2", "B"); map.put ("3", "C"); Iterator iterator = map.keyset (). Iterator (); while ( Iterator.hasnext ()) { String key = (String) Iterator.next (); if ("1". Equals (key) | | "2". Equals (key)) { iterator.remove (); //Add the line code Map.Remove (key);   } System.out.println (Map.get ("1")); System.out.println (Map.get ("2")); System.out.println (Map.get ("3"));
map<string,string> map = new hashmap<string,string> ();
Map.put ("1", "a");
Map.put ("2", "B");
Map.put ("3", "C");
Iterator iterator = Map.keyset (). iterator ();
while (Iterator.hasnext ()) {
string key = (String) iterator.next ();
if ("1". Equals (key) | | "2". Equals (Key)) {
iterator.remove (); Add the Line code
map.remove (key);
}
System.out.println (Map.get ("1"));
System.out.println (Map.get ("2"));
System.out.println (Map.get ("3"));
Error code reason: iterator works in a separate thread and owns a mutex lock. When the iterator is created, it creates a single chain index table that points to the original object, and when the original number of objects changes, the contents of the Index table do not change synchronously, so when the index pointer moves backwards, the object that is being iterated is not found. Iterator throws a java.util.ConcurrentModificationException exception.
So iterator is not allowed to be changed by the object of the iteration at work. However, you can delete an object by using the Remove () of the iterator itself, and the Iterator.remove () method keeps the index consistent while deleting the current iteration object.