Đoạn code sau cho kết quả gì?
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4));
for (Integer x : list) {
if (x == 2) {
list.remove(x);
}
}
System.out.println(list);
Xem đáp án và giải thích
Iterator của ArrayList là fail-fast: nó so sánh modCount mỗi lần next() và ném ConcurrentModificationException nếu list bị sửa ngoài iterator. Cách đúng là dùng list.removeIf(x -> x == 2) hoặc Iterator.remove(). Lưu ý exception này không đảm bảo luôn xảy ra (ví dụ xoá phần tử áp chót thì vòng lặp kết thúc sớm), nên đừng dựa vào nó để phát hiện lỗi.