中級 › 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です。イテレータ経由で消すit.remove()を使います。
次の問題