Question 1021
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(2);
list.add(3);
list.add(2);
for (int i = 0; i < list.size(); i++)
{
if (list.get(i) == 2)
{
list.remove(i);
}
}
System.out.println(list);
What is printed when the code segment executes?Main Solution
Solution:
Answer: B. Removing from an ArrayList while iterating with a forward index is the classic "skip-one-then-next" bug. Trace: start [1, 2, 2, 3, 2], i = 0 keeps 1; i = 1 removes the first 2, list becomes [1, 2, 3, 2]; after the update i = 2 now points at 3 (the second 2 slid into index 1 and was skipped); i = 3 points at 2, removed, list becomes [1, 2, 3]; i = 4 is no longer less than size() = 3, loop exits. The final list is [1, 2, 3] — one 2 "survives" because of the skip.
Answer: Correct: B
Answer images

