Developing Algorithms Using ArrayLists

AP Computer Science A· difficulty 4/5

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

What is printed?

  • A

    [2, 4]

    check_circle
  • B

    []

  • C

    [2, 3, 4]

  • D

    [1, 3, 5]

Explanation

The i-- after remove correctly compensates for the shift, removing all odd numbers and leaving [2, 4].

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

Related questions