ArrayList Methods

AP Computer Science A· difficulty 4/5

122 324 012 345

Given the ArrayList shown ([1,2,2,3,2,4]):

<code class="language-java">ArrayList<Integer> a = new ArrayList<>(Arrays.asList(1,2,2,3,2,4)); for (int i = 0; i < a.size(); i++) if (a.get(i) == 2) a.remove(i); </code></pre> What is the final state of <code>a</code>?

  • A

    IndexOutOfBoundsException

  • B

    [1, 2, 2, 3, 2, 4]

  • C

    [1, 2, 3, 4]

    check_circle
  • D

    [1, 3, 4]

Explanation

Removing without decrementing <code>i</code> skips the element shifted into the removed slot. Trace: at i=1 remove leaves [1,2,3,2,4], i becomes 2 (now 3), no remove; i=3 (now 2), remove leaves [1,2,3,4]; i=4 past size. Final: [1,2,3,4].

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

Related questions