Sie können die Liste nicht ändern, während Sie sie durchlaufen.
So können Sie list.remove("1")
innerhalb for (String x: list)
Schleife nicht aufrufen.
Schleife entfernen und einfach "1" Element entfernen.
Wenn Sie alle "1" Elemente entfernen Sie dies durch die folgenden Möglichkeiten:
while (list.remove("1")) {}
EDIT:
Hier dekompilierten wird Code von ArrayListIterator
Klasse, die verwendet wird, in for-Schleifen . Nach jeder Iteration next
Methode aufgerufen wird, kann in den ConcurrentModificationException
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;
}
}
Unsere Ausnahme von next
Verfahren unter den folgenden Bedingungen ausgelöst wird, geworfen werden:
if (ourList.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
Und unsere modCount
Variable wurde mit remove
Iteration geändert, so Der nächste next
Aufruf wird fehlschlagen.
wenn Sie entfernen möchten, entfernen Sie durch using index dh list.remove (list.indexOf (0); – emotionlessbananas
@holidayCoder Das wird auch in diesem Szenario nicht funktionieren. – Kayaman
@ user6328922 Überprüfen Sie diesen Link - http://www.journaldev.com/378/how- to-avoid-concurrentmodificationexception-wenn-mit-einem-iterator – Gandhi