Question 851
What is printed?
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) { list.add(i * i); }
for (int i = 0; i < list.size() - 1; i++) {
list.set(i, list.get(i) + list.get(i + 1));
}
System.out.println(list);Main Solution
Step 1: Build the initial list.
The first loop runs for i = 0, 1, 2, 3, 4 and adds i * i:
- i=0: 00 = 0
- i=1: 11 = 1
- i=2: 22 = 4
- i=3: 33 = 9
- i=4: 4*4 = 16
List after first loop: [0, 1, 4, 9, 16]
Step 2: Run the second loop.
The second loop runs while i < list.size() - 1, i.e., i < 4, so i = 0, 1, 2, 3. Each iteration sets list[i] = list[i] + list[i+1]. Crucially, each update is immediately visible to subsequent iterations because the list is modified in place.
- i=0: list[0] = list[0] + list[1] = 0 + 1 = 1 → list:
[1, 1, 4, 9, 16] - i=1: list[1] = list[1] + list[2] = 1 + 4 = 5 → list:
[1, 5, 4, 9, 16] - i=2: list[2] = list[2] + list[3] = 4 + 9 = 13 → list:
[1, 5, 13, 9, 16] - i=3: list[3] = list[3] + list[4] = 9 + 16 = 25 → list:
[1, 5, 13, 25, 16]
The last element (index 4) is never updated because the loop stops at i < 4. It remains 16.
Final output: [1, 5, 13, 25, 16], which is option D.
Teacher Explanation
This question tests understanding of in-place ArrayList mutation during iteration. The key insight is that each list.set(i, ...) immediately changes the value at index i, so subsequent iterations use the already-updated values — not the originals. Additionally, the loop condition i < list.size() - 1 means the last element (index 4) is never written to, so it stays at 16.
Education Coach Advice
When tracing ArrayList mutations in a loop, always update your mental model of the list after each iteration — don't assume the original values persist. Also, carefully check the loop's stopping condition: i < list.size() - 1 means the last index is excluded. On the AP exam, these boundary conditions are frequently tested.
Traps
Option A [1, 5, 13, 25, 25] is the most common trap. Students who correctly trace the first four updates but then assume the last element also gets updated (perhaps thinking the loop runs one more iteration, or that the last element becomes 25 by some other logic) will choose A. The loop condition i < list.size() - 1 (i.e., i < 4) stops at i=3, so index 4 is never touched and remains 16.
Option C [1, 4, 9, 16, 16] would result if students mistakenly used the original values for all additions (i.e., treated it as if a copy were used), but only for the first element being 1 — this is inconsistent reasoning.
Answer images

