This question already has an answer here:
@Test
public void testListCur(){
List<String> li=new ArrayList<String>();
for(int i=0;i<10;i++){
li.add("str"+i);
}
for(String st:li){
if(st.equalsIgnoreCase("str3"))
li.remove("str3");
}
System.out.println(li);
}
When I run this code,I will throw a ConcurrentModificationException.
It looks as though when I remove the specified element from the list,the list does not know its size have been changed.
I'm wondering if this is a common problem with collections and removing elements?
I believe this is the purpose behind the Iterator.remove() method, to be able to remove an element from the collection while iterating.
For example:
You could make a copy of list you want to remove element from, directly in for-each loop. For me, that is the simpliest way. Something like this:
Hope that will help you..
ArrayList has field
modCount
- count of collection modificationsWhen you invoke method
iterator()
creates new objectItr
. It has fieldexpectedModCount
.expectedModCount
field initialize bymodCount
value. When you invokemodCount
increments. When do you try access toli
via iterator checks thatexpectedModCount == modCount
and if it is false throws
ConcurrentModificationException
Hence if you get iterator and after collection modified - iterator is considered not valid and you cannot use it.
I think it is worth mentioning the Java 8 version
Try this (Java 8):