I have to questions. The first one is why when we run this function we have ConcurrentModificationException ?
public static void testList() {
List<String> list = new ArrayList<String>();
list.add("str3");
for (String st : list) {
if (st.equalsIgnoreCase("str3")) {
list.remove("str3");
}
}
System.out.println(list);
}
I thing, because enhanced for use Iterator (which checks modificationsCount
), but I ask to be sure. Is that the reason for the exception.
The second question is if I useCollections.synchronizedList(new LinkedList<Something>());
can I use 2 or more enhanced for loops? For example I have to threads and at some time the first one remove element from the collection and at some time the second one add elements in collection. I thing that it should be thread save even when we use iterator (I thing that enhanced for use iterator).
Thanks in advance.