Developing Algorithms Using ArrayLists

AP Computer Science A· difficulty 3/5

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

What is list after the loop?

  • A

    [2, 4]

  • B

    [1, 3]

    check_circle
  • C

    [1, 3, 4]

  • D

    [1, 2, 3, 4]

Explanation

Removing while incrementing skips elements; here both 2 and 4 happen to get removed correctly only with care, leaving [1,3].

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

Related questions