AP Computer Science A · Topic 7.4

Developing Algorithms Using ArrayLists Practice

Part of ArrayList.

Practice questions

31

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 31 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 2/5

    ArrayList<Integer> a = new ArrayList<>();
    a.add(1);
    a.add(2);
    a.add(3);
    ArrayList<Integer> b = new ArrayList<>();
    for (int x : a) b.add(x * 2);
    System.out.println(b);

    What is printed?

    • A

      [2, 4, 6]

      check_circle
    • B

      [1, 2, 3]

    • C

      [1, 4, 9]

    • D

      []

    Why

    Each element of a is doubled and added to b: 1<em>2=2, 2</em>2=4, 3*2=6.

  2. Sample 2difficulty 2/5

    int[] arr = {3, 1, 4, 1, 5};
    ArrayList<Integer> list = new ArrayList<>();
    for (int x : arr) list.add(x);
    System.out.println(list.size());

    What is printed?

    • A

      0

    • B

      4

    • C

      3

    • D

      5

      check_circle

    Why

    Each of the 5 elements is added to the list, so size is 5.

  3. Sample 3difficulty 2/5

    ArrayList<Integer> list = new ArrayList<>();
    list.add(5);
    list.add(2);
    list.add(5);
    list.add(7);
    list.add(5);
    list.add(2);
    int count = 0;
    for (int x : list) {
        if (x == 5) count++;
    }
    System.out.println(count);

    What is printed?

    • A

      2

    • B

      4

    • C

      0

    • D

      3

      check_circle

    Why

    The value 5 appears at indices 0, 2, and 4. Count = 3.

  4. Sample 4difficulty 3/5

    ArrayList<Integer> list = new ArrayList<>();
    list.add(1); list.add(2); list.add(3); list.add(4);
    for (int i = 0; i < list.size(); i++) {
      if (list.get(i) % 2 == 0) {
        list.remove(i);
      }
    }

    What is list after the loop?

    • A

      [2, 4]

    • B

      [1, 3]

      check_circle
    • C

      [1, 3, 4]

    • D

      [1, 2, 3, 4]

    Why

    Removing while incrementing skips elements; here both 2 and 4 happen to get removed correctly only with care, leaving [1,3].

  5. Sample 5difficulty 3/5

    ArrayList<Integer> list = new ArrayList<>();
    list.add(2); list.add(2); list.add(3); list.add(4);
    for (int i = 0; i < list.size(); i++) {
      if (list.get(i) == 2) {
        list.remove(i);
      }
    }

    What does list contain?

    • A

      []

    • B

      [3, 4]

    • C

      [2, 2, 3, 4]

    • D

      [2, 3, 4]

      check_circle

    Why

    After removing index 0, the second 2 shifts to index 0 but i becomes 1, skipping it.