How to avoid ConcurrentModificationException for map or List

ConcurrentModificationException exception is occurred because of while one thread is iterating the collections and other thread trying to modify the object in collections. This will be happened for below map and list of collections. 1. Modifying state of any key or value in map implementations(example,HashMap,HashTable,LinkedHashMap) during iteration of Map objects 2.Adding/remove(Iterator.remove) the object in a collections class while iteration of collection of objects at the same time. you can use ConcurrentHashMap for avoiding this exception but there is no guarantee of all your objects are iterated. Solution is use map.entrySet for modifying object while iteration HashMap mapDemo = new HashMap(); mapDemo.put("key-1", "value-1"); mapDemo.put("key-2", "value-2"); mapDemo.put("key-3", "value-3"); for (Map.Entry entry : mapDemo.entrySet()) { if (entry.getKey().contains("key-2")){ entry.setValue("new Value-2"); } } for (Map.Entry entry : mapDemo.entrySet()) { System.out.println(entry.getKey()+"==="+entry.getValue()); } } and the output is:- key-1===value-1 key-2===new Value-2 key-3===value-3

No comments:

Post a Comment

Note: only a member of this blog may post a comment.