Code Fix

中級 › ConcurrentModificationException の原因と直し方 › パターン4

ConcurrentModificationException の原因と直し方

ループ中のリスト変更で発生します。

 1  import java.util.ArrayList;
 2  import java.util.Iterator;
 3  import java.util.List;
 4  
 5  public class Main {
 6      public static void main(String[] args) {
 7          List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4));
 8          Iterator<Integer> it = list.iterator();
 9          while (it.hasNext()) {
10              int n = it.next();
11              if (n % 2 == 0) _______________________________;
                                               ^
12          }
13          System.out.println(list);
14      }
15  }
Exception in thread "main" java.util.ConcurrentModificationExceptionexited with code 1

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

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

ConcurrentModificationException の原因と直し方

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

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

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