Traversing ArrayLists

AP Computer Science A· difficulty 4/5

Safely remove all elements equal to 0:

  • A

    for (int i = list.size() - 1; i >= 0; i--) if (list.get(i) == 0) list.remove(i);

  • B

    for-each with remove

  • C

    Both work; second avoids index shifting issues

    check_circle
  • D

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

Explanation

Iterating backwards avoids skipping after removal.

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

Related questions