Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Putting into HashMap at 0 index is causing ConcurrentModificationException

I have a simple HashMap algorithm:

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();
    if (key.equals(2)) {
        map.put(1, 2);
    }
}

and this is working fine. But when I will modify the condition body to:

if (key.equals(2)) {
    map.put(0, 2); // changed index '1' to '0'
}

it’s always throwing java.util.ConcurrentModificationException. The same is happening for key values lesser than 0.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I missing?


Edit

Seems that if I will remove the third Map element:

map.put(1, 1);
map.put(2, 2);
// map.put(3, 3);

it’s working fine

>Solution :

You are changing the size of the map during iteration which causes the exception. Keep in mind that it is not put operation that throws the exception but an attempt to get next element via iterator via Iterator#next

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading