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);
int i = 0;
while (i < list.size()) {
    if (list.get(i) % 2 == 0) {
        list.remove(i);
    } else {
        i++;
    }
}
System.out.println(list);

What is printed?

  • A

    [1, 2, 3]

  • B

    [1, 3, 4]

  • C

    [2, 4]

  • D

    [1, 3]

    check_circle

Explanation

The fix is to only increment i when nothing was removed. This correctly removes all even numbers, leaving [1, 3].

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

Related questions