I have this little piece of code and it gives me the concurrent modification exception. I cannot understand why I keep getting it, even though I do not see any concurrent modifications being carried out.
import java.util.*;
public class SomeClass {
public static void main(String[] args) {
List<String> s = new ArrayList<>();
ListIterator<String> it = s.listIterator();
for (String a : args)
s.add(a);
if (it.hasNext())
String item = it.next();
System.out.println(s);
}
}
to understand this lets look at source of HashMap implementation:
which contains HashIterator as below:
every time you create a iterator:
to avoid this u can:
this will allow you to iterate and add or remove elements at the same time without rising an exception
More info on CopyOnWriteArrayList
You are not allowed to continue iterating over an iterator after the underlying list is modified. Here you create the iterator before adding a few items to
s
, and then proceed to do ahasNext()
and anext()
on it after the additions, leading to theConcurrentModificationException
Have a look at oracle documentation page.
In your case, you have modified the collection after creating the iterator and hence you have encountered the exception.
If you change your code as per Stephen C answer, you won't get this error.