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]
- Ccheck_circle
[1, 2, 3, 4]
- 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].