Gặp ConcurrentModificationException.
Iterator của các collection trong java.util là fail-fast: nó nhớ modCount lúc tạo và so lại ở mỗi lần next(); gọi list.remove(...) trực tiếp làm modCount lệch → ném exception ngay.
java
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
for (String s : list) {
if (s.equals("b")) list.remove(s); // ConcurrentModificationException
}Ba cách xóa đúng:
java
list.removeIf(s -> s.equals("b")); // Java 8+, gọn nhất
Iterator<String> it = list.iterator(); // xóa qua chính iterator
while (it.hasNext()) {
if (it.next().equals("b")) it.remove();
}
for (int i = list.size() - 1; i >= 0; i--) { // duyệt ngược theo index
if (list.get(i).equals("b")) list.remove(i);
}Bẫy phụ: xóa phần tử áp chót trong for-each lại không ném exception — sau khi xóa, cursor bằng size nên hasNext() trả false và vòng lặp kết thúc sớm, bỏ sót phần tử cuối.
Đây là lý do không nên dựa vào việc "không thấy lỗi" để kết luận code đúng.