反復処理中にリストを変更することはできません。
list.remove("1")
のループ内にfor (String x: list)
を呼び出すことはできません。
ループを削除し、単に "1"要素を削除します。
次のことで、あなたがこれを行うことができ、すべての「1」の要素を削除する場合:
while (list.remove("1")) {}
編集:ここでは
がArrayListIterator
クラスのコードを逆コンパイルされ、それが中に使用されているため、ループ。各反復next
メソッドが呼び出された後、どこConcurrentModificationException
がスローすることができ
私たちの例外は、以下の条件に
next
メソッドからスローされ
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;
}
}
:
if (ourList.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
そして、我々のmodCount
変数はそう、remove
反復で変更されました次のnext
コールは失敗します。あなたはArrayListの中に2つの要素を持っている場合にのみ、
削除したい場合は、によって削除 list.remove(list.indexOf(0); – emotionlessbananas
@holidayCoderこのシナリオでは動作しません。 – Kayaman
@ user6328922このリンクをチェックしてください - http://www.journaldev.com/378/how-イテレータを使用している場合の避けるコンカレントな変更の修正 – Gandhi