Code Fix

中級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

空欄を埋めてビルドを通す

広告
広告スロット(未設定)

ConcurrentModificationException の原因と直し方

removeIf、Iterator、逆順ループの3つの解法を比較します。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)