The following code throws the concurrent modification exception
import java.util.*;
public class SampleTest
{
public static void main(String[] args) {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put("value1","a");
map.put("value2","b");
map.put("value3","c");
map.put("value4","d");
map.put("value5","e");
// sublists
List<LinkedHashMap<String, String>> subList = new ArrayList<>();
for(int i = 0; i<5; i++) {
subList.add(map);
}
List<List<LinkedHashMap<String, String>>> mainList = new LinkedList<>();
for(int i = 0; i<3; i++)
{
mainList.add(subList);
}
List<LinkedHashMap<String,String>> temp = mainList.get(mainList.size() - 1);
List<LinkedHashMap<String,String>> temp2 = mainList.get(mainList.size() - 2);
for(LinkedHashMap<String,String> map2 : temp) {
temp2.add(map); // Exception Thrown Here......
}
}
}
However i fixed the code by creating a new List and add the map and finally add the new list outside the loop in temp2
example,
List<LinkedHashMap<String,String>> pp = new ArrayList<>();
for(LinkedHashMap<String,String> map2 : temp) {
pp.add(map);
}
temp2.addAll(pp);
I would like to know in detail why the concurrent happens in the earlier code.
Thanks.