AP Computer Science A · Topic 7.1

Introduction to ArrayList Practice

Part of ArrayList.

Practice questions

15

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

  1. Sample 1difficulty 2/5

    ArrayList<Integer> list = new ArrayList<>();
    list.add(7);
    list.add(8);
    int x = list.get(0) + list.get(1);
    System.out.println(x);

    What is printed?

    • A

      Compile-time error

    • B

      7

    • C

      15

      check_circle
    • D

      78

    Why

    Autoboxing converts int 7 and 8 into Integer objects when added. Auto-unboxing converts them back to int when adding, producing 15.

  2. Sample 2difficulty 2/5

    ArrayList<Integer> list = new ArrayList<>();
    int sum = 0;
    for (int x : list) sum += x;
    System.out.println(sum + " " + list.size());

    What is printed?

    • A

      Runtime error

    • B

      0 1

    • C

      1 0

    • D

      0 0

      check_circle

    Why

    The list is empty so the for-each loop never executes, sum stays 0, and size is 0.

  3. Sample 3difficulty 2/5

    ArrayList<Integer> list = new ArrayList<>();
    for (int i = 1; i <= 5; i++) list.add(i);
    int s = 0;
    for (int x : list) s += x;
    System.out.println(s);

    What is printed?

    • A

      Compile-time error

    • B

      5

    • C

      10

    • D

      15

      check_circle

    Why

    The loop adds 1, 2, 3, 4, 5 to the list. Summing them with the for-each loop gives 1+2+3+4+5 = 15. Autoboxing converts each int to an Integer when adding.

  4. Sample 4difficulty 2/5

    Which is a correct ArrayList declaration?

    • A

      ArrayList list = new ArrayList(int);

    • B

      ArrayList<Integer> list = new ArrayList<>();

      check_circle
    • C

      ArrayList<int> list = new ArrayList<int>();

    • D

      ArrayList<int> list = new ArrayList<>();

    Why

    Generic type parameter must be a reference type; use <code>Integer</code> (not <code>int</code>).

  5. Sample 5difficulty 3/5

    <code>ArrayList<int></code> is

    • A

      Compile error (can only use reference types)

      check_circle
    • B

      Valid (will autobox)

    • C

      Slow but works

    • D

      Compiles only with --enable-experimental

    Why

    Generic type parameters must be reference types; use Integer, Double, etc.