When iterator. hasnext () is used to operate on the iterator, if the iteration object changes at this time, such as inserting new data or deleting data.
The following exception is reported:
Java. util. concurrentmodificationexception
At java. util. hashmap $ hashiterator. nextentry (hashmap. Java: 793)
At java. util. hashmap $ keyiterator. Next (hashmap. Java: 828)
For example:Program(Transferred from the Internet ):
Mport Java. util. *; public class main {public static void main (string ARGs []) {main = new main (); main. test () ;}public void test () {map BB = new hashmap (); bb. put ("1", "WJ"); bb. put ("2", "ry"); iterator it = BB. keyset (). iterator (); While (it. hasnext () {object ele = it. next (); bb. remove (Ele); // wrong} system. out. println ("success! ");}}
Cause: When iterator performs traversal, hashmap is modified (BB. remove (Ele), size-1), iterator (Object ele = it. next () checks the size and size of the hashmap and throws the concurrentmodificationexception error.
Solution:
1) Modify hashtable through iterator
While (it. hasnext ()){
Object ele = it. Next ();
It. Remove ();
}
2) depending on the actual program, you can manually lock the program that iterator traverses and lock the program that modifies hashmap.
3) Replace hashmap with "concurrenthashmap". concurrenthashmap checks the modification operation and locks it. It can also be used for insert operations.
Import java. util. Concurrent .*;