中級 › ConcurrentModificationException の原因と直し方 › パターン2
ConcurrentModificationException の原因と直し方
ループ中のリスト変更で発生します。
1 import java.util.ArrayList; 2 import java.util.List; 3 4 public class Main { 5 public static void main(String[] args) { 6 List<Integer> list = new ArrayList<>(List.of(1, 2, 3)); 7 for (int i = _______________; i >= 0; i--) { ^ 8 if (list.get(i) == 2) list.remove(i); 9 } 10 System.out.println(list); 11 } 12 }
Exception in thread "main" java.lang.IndexOutOfBoundsExceptionexited with code 1
空欄を埋めてビルドを通す
添字で削除するときは後ろから回します。前から削ると以降の要素が繰り上がって位置がずれます。
次の問題