Java iterator and ConcurrentModificationException

What will produce the following code:

List names = new ArrayList(Arrays.asList("1", "2,", "3"));
Iterator iterator = names.iterator();
System.out.println(iterator.next());
iterator.remove();
System.out.println(iterator.next());
System.out.println(names);

List names2 = new ArrayList(Arrays.asList("4", "5,", "6"));
Iterator iterator2 = names2.iterator();
System.out.println(iterator2.next());
names2.remove(2);
System.out.println(iterator2.next());
System.out.println(names2);

Output:

1
2,
[2,, 3]
4
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at com.sabre.ticketing.emd.mt.Accc.main(Accc.java:31)

Notes:
Once you access iterator you can only modify array state via that iterator by e.g. iterator.remove(). However, call to remove on a list reference (outside the iterator) increases modcount and subsequent call to iterator.next() will throw ConcurrentModificationException

ArrayList:
public E remove(int index) {
RangeCheck(index);
modCount++; // note: modcount is increased vs expectedModCount
...

AbstractList.Itr:

public E next() {
checkForComodification();
...

final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}

public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();

try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount; // note: modcount is not increased vs expectedModCount
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s