ArrayList Methods

AP Computer Science A· difficulty 4/5

Consider:

<code class="language-java">ArrayList<int[]> list = new ArrayList<>(); int[] x = {1, 2}; list.add(x); list.add(x); list.get(0)[0] = 99; list.set(1, new int[]{7, 8}); System.out.print(list.get(0)[0] + "," + list.get(1)[0]); </code></pre> What is printed?

  • A

    99,99

  • B

    1,7

  • C

    1,1

  • D

    99,7

    check_circle

Explanation

Both list slots reference the same array <code>x</code>, so mutating element 0 via <code>list.get(0)</code> updates the shared array, but <code>set(1, new int[]{7,8})</code> REPLACES the second reference with a new array. Index 0 still points at the mutated x (99), index 1 points at {7,8}.

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

Related questions