AP Computer Science A · Topic 7.2

ArrayList Methods 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

    for (int i = 1; i <= list.size(); i++) {
        System.out.println(list.get(i));
    }

    What is the bug?

    • A

      ArrayList lacks a get method

    • B

      Nothing is wrong

    • C

      println cannot accept an Object

    • D

      Indices start at 0 and end at size()-1; should be i = 0; i < list.size()

      check_circle

    Why

    Java collections are zero-indexed. Starting at 1 skips the first element and going through size() throws IndexOutOfBoundsException.

  2. Sample 2difficulty 2/5

    ArrayList<String> list = new ArrayList<>();
    list.add("a");
    list.add("b");
    list.add("c");
    list.remove(1);
    System.out.println(list.size());

    What is printed?

    • A

      2

      check_circle
    • B

      1

    • C

      3

    • D

      0

    Why

    Three elements are added, then one is removed. The size is now 3 - 1 = 2.

  3. Sample 3difficulty 2/5

    Get element at index 2 of an ArrayList:

    • A

      list.get(2)

      check_circle
    • B

      list.at(2)

    • C

      list[2]

    • D

      list.element(2)

    Why

    ArrayList uses methods, not bracket notation.

  4. Sample 4difficulty 2/5

    ArrayList<Integer> list = new ArrayList<>();
    list.add(10);
    list.add(20);
    list.add(30);
    list.add(40);
    int sum = list.get(0) + list.get(list.size() - 1);
    System.out.println(sum);

    What is printed?

    • A

      60

    • B

      30

    • C

      50

      check_circle
    • D

      100

    Why

    First element 10 plus last element 40 equals 50.

  5. Sample 5difficulty 2/5

    ArrayList<Integer> list = new ArrayList<>();
    list.add(10);
    list.add(20);
    list.add(30);
    list.set(1, 99);
    System.out.println(list.get(1));

    What is printed?

    • A

      30

    • B

      10

    • C

      20

    • D

      99

      check_circle

    Why

    set(1, 99) replaces the element at index 1 with 99. get(1) returns the new value 99.