Developing Algorithms Using ArrayLists

AP Computer Science A· difficulty 4/5

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]

  • C

    [2, 2]

    check_circle
  • 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.

Want 10 more like this — adaptive to your weak spots?

Related questions