ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
for (Integer i : list)
    if (i == 2) list.remove(i);
System.out.print(list);
  1. A. [1, 2]
  2. B. ConcurrentModificationException is thrown
  3. C. [2, 3]
  4. D. [1, 3]

Correct answer: D. [1, 3]

list.remove(i) with an Integer removes the value 2. The size drops to 2 while the iterator's cursor is already 2, so hasNext() returns false and the loop ends before next() can detect the change. Removing any other element here would throw ConcurrentModificationException.

More OOP with C++ and Java questions

Exams that ask this topic