ArrayList<Integer> list = new ArrayList<>();
list.add(2);
list.add(2);
list.add(2);
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?
- A
[]
- B
[2, 2, 2, 2]
- Ccheck_circle
[2, 2]
- D
[2]
Explanation
This is the classic remove-while-iterating bug. After removing index 0, elements shift left, so i increments past the next 2. Indices visited: 0 (remove), 1 was originally index 2 (remove), leaving two 2s untouched.