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 mo
to understand this lets look at source of HashMap implementation:
public class HashMap extends AbstractMap implements Cloneable, Serializable{
which contains HashIterator as below:
private abstract class HashIterator {
...
int expectedModCount = modCount;
...
HashMapEntry nextEntry() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
....
}
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
Concurrency map/list iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.
More info on CopyOnWriteArrayList