I am in a very peculiar state. I have a list similar to below: -
List<String> list = new ArrayList<String>(); list.add("a"); list.add("b");
Now, when I perform several types of movements, for example, using the extended for, iterator and normal loop, the following code snippets are given: -
1> Advanced Loop: -
try { for(String a : list) { System.out.println(a); list.add("f"); } } catch (Exception e) { e.printStackTrace(); }
2> Iterator: -
try { Iterator<String> itr = list.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); list.add("f"); } } catch (Exception e) { e.printStackTrace(); }
3> Normal cycle: -
for (int i=0;i<list.size();i++) { System.out.println(list.get(i)); list.add("f"); }
Now, the special problem is that when using the extended for-loop and iterator, I get the following exception: -
java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source) the reason i know, that while iterating through a list, one cannot modify it parallely.
but when I use the normal loop, it works correctly, am I missing something ??
Please, help!!!..
source share