ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
int i = 0;
while (i < list.size()) {
if (list.get(i) % 2 == 0) {
list.remove(i);
} else {
i++;
}
}
System.out.println(list);What is printed?
- A
[1, 2, 3]
- B
[1, 3, 4]
- C
[2, 4]
- Dcheck_circle
[1, 3]
Explanation
The fix is to only increment i when nothing was removed. This correctly removes all even numbers, leaving [1, 3].