ควิซ Java: Iterators & ConcurrentModificationException

This hard Java quiz is about changing a collection while you iterate over it. You will see when the for-each loop throws ConcurrentModificationException (and the odd case where it does not), and practice the safe ways: Iterator.remove(), removeIf(), ListIterator and CopyOnWriteArrayList.

ยาก 10 ข้อ ~8 นาที ผ่านที่ 80% Java 17

เลือกโหมด

กำลังเล่นแบบผู้เยี่ยมชม: เข้าสู่ระบบเพื่อเก็บ XP และ streak

ตัวอย่างคำถาม

ข้อ 1 จาก 10

What happens when you run this?

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4));
        for (Integer n : list) {
            if (n == 2) list.remove(n);
        }
        System.out.println(list);
    }
}
ดูเฉลย

A. ConcurrentModificationException The for-each loop uses a hidden iterator. Removing through the list itself changes its modification count, and the iterator's next next() call notices and throws ConcurrentModificationException.

ควิซนี้มีเนื้อหาอะไรบ้าง

  • Why removing inside a for-each loop throws
  • Iterator.remove() and its rules
  • removeIf() as the simple fix
  • Index loops that skip elements
  • ListIterator.add() and CopyOnWriteArrayList

คำถามที่พบบ่อย

ต้องมีบัญชีไหม?

ไม่ต้อง ใครก็เล่นได้ เข้าสู่ระบบเพื่อเก็บ XP, streak, เหรียญตรา และประวัติ

ทำซ้ำได้ไหม?

ได้ ระบบเก็บคะแนนที่ดีที่สุดไว้ และสลับคำถามกับตัวเลือกใหม่ทุกครั้ง