Developing Algorithms Using ArrayLists

AP Computer Science A· difficulty 4/5

ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(3);
list.add(5);
list.add(7);
int v = 4;
int i = 0;
while (i < list.size() && list.get(i) < v) i++;
list.add(i, v);
System.out.println(list);

What is printed?

  • A

    [1, 3, 4, 5, 7]

    check_circle
  • B

    [1, 3, 5, 4, 7]

  • C

    [4, 1, 3, 5, 7]

  • D

    [1, 3, 5, 7, 4]

Explanation

The loop stops at the first element >= 4, which is 5 at index 2. Inserting 4 at index 2 gives [1, 3, 4, 5, 7].

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

Related questions