Why don't I get a "ConcurrentModificationException" while iterating and changing to a HashMap at the same time?

I have a card

Map<String, String> map = new HashMap<String, String>();

map.put("Pujan", "pujan");
map.put("Swati", "swati");
map.put("Manish", "manish");
map.put("Jayant", "jayant");
Iterator<Map.Entry<String, String>> itr = map.entrySet().iterator();
while(itr.hasNext()){
  Entry<String,String> entry=(Entry<String, String>) itr.next();
  map.put("Manish", "Updated");
}

I am not getting an exception here (where I am trying to modify the existing value of the Manish key). But if I try to add a new key map.put("Manish123", "Updated"), I get ConcurrentModificationException.

+4
source share
3 answers

Since you do not change iterator,

putwill mutate an existing record in this case, because Map.Entrythe same key already exists in Map.

+4
source

If you see Javadoc for the modCountHashMap field (in the Java 8 source HashMap.java), you will see:

/**
 * The number of times this HashMap has been structurally modified.
 * Structural modifications are those that change the number of mappings in
 * the HashMap or otherwise modify its internal structure (e.g.,
 * rehash).  This field is used to make iterators on Collection-views of
 * the HashMap fail-fast.  (See ConcurrentModificationException).
 */

, , . ConcurrentModificationException ( ), expectedModCount ( modCount , , Iterator<Map.Entry<String, String>> itr = map.entrySet().iterator();) modCount, , (, put , ). , . , , ).

, - ( , ). , , Manish Updated , ( 4 ). , , , ConcurrentModificationException.

(: ):

    List<String> names = Arrays.asList("Larry", "Moe", "Curly");
    int i = 0;
    Iterator<String> strIter = names.iterator();
    while (strIter.hasNext()) {
        names.set(i, strIter.next() + " " + i); // value changed, no structural modification to the list
        i += 1;
    }
    System.out.println(names);

:

[Larry 0, Moe 1, Curly 2]
0

Java API: Iterator ConcurrentModificationException, Collection , .

Java , , Iterator .

Java

javaAs , , Collection . , , . , , ConcurrentModificationException.

Java- , , " ". . , , , , Iteration - , . , JDK1.4, , Vector, ArrayList, HashSet ..

java

Unlike the fail-safe Iterator, the fail-safe iterator does not throw an exception if the assembly changes structurally while one thread iterates over it because they work with the Collection clone instead of the original collection, and therefore they are called a fail-safe iterator. The CopyOnWriteArrayList iterator is an example of a failover Iterator, the iterator, written by the ConcurrentHashMap keySet, is also a failover iterator and never throws a ConcurrentModificationException in Java.

-1
source

All Articles