Is there any way I can modify the HashMap
values of a particular key while iterating over it?
A sample program is given below:
public static void main(String[] args) {
HashMap<Integer,ArrayList<String>> hm = new HashMap<Integer, ArrayList<String>>();
ArrayList<String> ar = new ArrayList<String>();
for(int i=0;i<50;i++){
ar.add(Integer.toString(i));
}
hm.put(1, ar);
for(String s:hm.get(1)){
hm.get(1).add("hello");
}
}
Error Thrown:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at Excp.main(Excp.java:17)
This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
Below peice of code is causing the problem.
for(String s:hm.get(1)){
hm.get(1).add("hello");
}
You are iterating and modifying the same. Avoid this by creating new ArrayList
ArrayList<String> ar1 = new ArrayList<String>();
for (String s : hm.get(1)) {
ar1.add("hello");
}
have a read here