TransWikia.com

Why does adding an element in an IF block work while iterating over HashMap?

Stack Overflow Asked by A Nice Guy on January 8, 2021

Why does adding an element into a HashMap work inside an IF block while iterating it using an iterator?

    HashMap<Integer, Integer> map = new HashMap<>();  
    map.put(1, 1);  
    map.put(2, 2);  
    map.put(3,3);  
      
    Iterator<Integer> it = map.keySet().iterator();  
    while(it.hasNext()) {  
        Integer key = it.next();  
        System.out.println("Map Value:" + map.get(key));  
        if (key.equals(2)) {  
            map.put(1, 4);                                 // Works, Why?
        }  
        //map.put(5, 5);                                   // ConcurrentModificationException, as expected
    } 

Please point me to any duplicates, if any, I’ll delete this question.

One Answer

You are just updating the value inside the map for key 1 in the if while outside of the if you add a new key with 5 making the size of the map bigger. Therefore you are modifying the size and the iterator fails.

In general: If you want to compare why one call works and the other not, make sure you are using exactly the same call with the same parameters. So map.put(1,4) will work to outside the if.

Correct answer by WarrenFaith on January 8, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP