HashMap reverses < value,key > Why an error is reported

reverse the value,key of hashMap

</span>

Exception in thread "main" java.util.ConcurrentModificationException
    at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1493)
    at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1516)
    at com.test.TestHashtable.main(TestHashtable.java:18)

I don"t know what the reason is.
I used to learn JS, and now I am just learning java

Jul.22,2021

because you perform a new operation while traversing HashMap, HashMap is not allowed, you can try to use a new HashMap to store inverted key-value pairs. Use a common noun to explain it as fail-fast , you can find out.


should be caused by the addition of key when you loop with hashMap's keys. Create a new hashmap to reverse


HashMap
if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
 ConcurrentHashMap
Map<String,String> map = new ConcurrentHashMap<String,String>();
        map.put("adc", "");
        map.put("apc", "");
        map.put("t", "");
        
        for (String key : map.keySet()) {
            String value = map.get(key);
            map.put(value, key);
        }

this for is written in iterator mode.
that is, the elements to be traversed are decided before you start the loop.
when you modify the iterator while traversing, the iterator should be modified accordingly, in violation of design principles, so it is not allowed.
similar errors are deleted when traversing list.

Menu