Traversing ArrayLists

AP Computer Science A· difficulty 4/5

for (int i = 0; i < list.size(); i++) {
    if (list.get(i) == 0) {
        list.remove(i);
    }
}

What is the bug?

  • A

    ArrayList does not support remove

  • B

    After remove, indices shift; the next element is skipped

    check_circle
  • C

    remove takes a value, not an index

  • D

    Nothing is wrong

Explanation

Removing element at index i shifts later elements down by one, but i still increments, so the new element at index i is skipped. Iterate backwards or decrement i after removal.

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

Related questions