You can't change list while iterating through it.
So you can't call list.remove("1")
inside for (String x: list)
loop.
Remove loop and simply remove "1" element.
If you want to remove all "1" elements you can do this by the following:
while (list.remove("1")) {}
EDIT:
Here is decompiled code of ArrayListIterator
class, that is used in for-loops. After each iteration next
method is called, where ConcurrentModificationException
can be thrown
private class ArrayListIterator implements Iterator<E> {
/** Number of elements remaining in this iteration */
private int remaining = size;
/** Index of element that remove() would remove, or -1 if no such elt */
private int removalIndex = -1;
/** The expected modCount value */
private int expectedModCount = modCount;
public boolean hasNext() {
return remaining != 0;
}
@SuppressWarnings("unchecked") public E next() {
ArrayList<E> ourList = ArrayList.this;
int rem = remaining;
if (ourList.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
if (rem == 0) {
throw new NoSuchElementException();
}
remaining = rem - 1;
return (E) ourList.array[removalIndex = ourList.size - rem];
}
public void remove() {
Object[] a = array;
int removalIdx = removalIndex;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
if (removalIdx < 0) {
throw new IllegalStateException();
}
System.arraycopy(a, removalIdx + 1, a, removalIdx, remaining);
a[--size] = null; // Prevent memory leak
removalIndex = -1;
expectedModCount = ++modCount;
}
}
Our exception is thrown from next
method in the following condition:
if (ourList.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
And our modCount
variable was changed with remove
iteration, so the next next
call will fail.