When using the Iterator.hasnext () operation iterator, if the object at this time of iteration changes, such as inserting new data, or having data deleted.
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 the following program (transferred from the Internet):
[Java]View Plaincopyprint?
- Mport java.util.*;
- Public class Main
- {
- Public static void Main (String args[])
- {
- Main 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!");
- }
- }
Mport java.util.*;p ublic class main{public static void Main (String args[]) {Main 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 (); It.hasnext ()) {Object ele = It.next (); Bb.remove (ele); Wrong}system.out.println ("success!");}}
Cause: Iterator do traversal, HashMap is modified (Bb.remove (ele), size-1), Iterator (Object ele=it.next ()) will check HashMap size,size change, Throws an error concurrentmodificationexception.
Workaround:
1) Modify Hashtable while (It.hasnext ()) {Object ele = It.next () via iterator; It.remove (); }
2) According to the actual program, you manually to the iterator traversal of the program lock, to modify the HashMap of the program and lock.
3) Replace Hashmap,concurrenthashmap with "Concurrenthashmap" to check for modifications, lock them, or insert them. Import java.util.concurrent.*;
Java.util.ConcurrentModificationException Solutions