AP Computer Science A · Topic 7.3
Traversing ArrayLists Practice
Part of ArrayList.
Practice questions
20
Sample questions
5 of 20 — sign in to practice the rest with adaptive difficulty and mastery tracking.
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
- Bcheck_circle
list.size()
- C
list.length()
- D
list.length
Why
ArrayList uses size(), a method call. length is a property of arrays, and length() applies to Strings.
- A
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?
- Acheck_circle
10
- B
8
- C
11
- D
3
Why
"hi"=2, "hello"=5, "hey"=3. Sum = 2+5+3 = 10.
- A
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]
- Ccheck_circle
[11, 21, 31]
- D
[10, 20, 30]
Why
Each element is replaced by itself plus 1: 11, 21, 31.
- A
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
- Ccheck_circle
38
- D
30
Why
a = [1,4,9,16]. a.set(2, 1+16=17) -> [1,4,17,16]. Sum = 38.
- A
Sample 5difficulty 3/5
Sum all integers in <code>ArrayList<Integer> list</code>:
- Acheck_circle
for (int x : list) sum += x;
- 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>).
- A