Developing Algorithms Using ArrayLists

AP Computer Science A· difficulty 3/5

ArrayList<Integer> list = new ArrayList<>();
list.add(2); list.add(2); list.add(3); list.add(4);
for (int i = list.size() - 1; i >= 0; i--) {
  if (list.get(i) == 2) {
    list.remove(i);
  }
}

What does list contain?

  • A

    [2, 3, 4]

  • B

    [3, 4]

    check_circle
  • C

    [2, 2, 3, 4]

  • D

    []

Explanation

Iterating in reverse safely removes all matching elements.

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

Related questions