AP Computer Science A · Topic 7.3

Traversing ArrayLists Practice

Part of ArrayList.

Practice questions

20

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 20 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 2/5

    public static int sum(ArrayList<Integer> list) {
        int total = 0;
        for (int i = 0; i < /* missing */; i++) {
            total += list.get(i);
        }
        return total;
    }

    Which expression correctly replaces /* missing */?

    • A

      list.size

    • B

      list.size()

      check_circle
    • C

      list.length()

    • D

      list.length

    Why

    ArrayList uses size(), a method call. length is a property of arrays, and length() applies to Strings.

  2. Sample 2difficulty 2/5

    ArrayList<String> list = new ArrayList<>();
    list.add("hi");
    list.add("hello");
    list.add("hey");
    int total = 0;
    for (String s : list) total += s.length();
    System.out.println(total);

    What is printed?

    • A

      10

      check_circle
    • B

      8

    • C

      11

    • D

      3

    Why

    "hi"=2, "hello"=5, "hey"=3. Sum = 2+5+3 = 10.

  3. Sample 3difficulty 2/5

    ArrayList<Integer> list = new ArrayList<>();
    list.add(10);
    list.add(20);
    list.add(30);
    for (int i = 0; i < list.size(); i++) {
        list.set(i, list.get(i) + 1);
    }
    System.out.println(list);

    What is printed?

    • A

      [11, 22, 33]

    • B

      [1, 2, 3]

    • C

      [11, 21, 31]

      check_circle
    • D

      [10, 20, 30]

    Why

    Each element is replaced by itself plus 1: 11, 21, 31.

  4. Sample 4difficulty 3/5

    import java.util.ArrayList;
    public static int run() {
        ArrayList<Integer> a = new ArrayList<>();
        for (int i = 1; i <= 4; i++) a.add(i * i);
        a.set(2, a.get(0) + a.get(3));
        int s = 0;
        for (int v : a) s += v;
        return s;
    }
    // Call: System.out.println(run());

    What is printed?

    • A

      33

    • B

      29

    • C

      38

      check_circle
    • D

      30

    Why

    a = [1,4,9,16]. a.set(2, 1+16=17) -> [1,4,17,16]. Sum = 38.

  5. Sample 5difficulty 3/5

    Sum all integers in <code>ArrayList<Integer> list</code>:

    • A

      for (int x : list) sum += x;

      check_circle
    • B

      Both work; first is enhanced-for, second uses size()

    • C

      for (int i = 0; i < list.length; i++) sum += list[i];

    • D

      Cannot iterate

    Why

    First works (with auto-unboxing); second has wrong syntax (use <code>list.size()</code> and <code>list.get(i)</code>).