Unit 4 Day 21 Arraylist Comprehensive

Unit 4: Data Collections
Day 21 Practice - January 21, 2026Cycle 1 - Hard
Focus: Comprehensive ArrayList Operations

Practice Question

Consider the following code segment:
ArrayList<Integer> data = new ArrayList<>();
data.add(10);
data.add(20);
data.add(30);
data.add(1, 15);
data.set(2, 25);
data.remove(0);
data.add(data.get(0));

System.out.println(data);
What is printed as a result of executing this code segment?
Difficulty: Hard - Time: 4-5 minutes - AP Skill: 2.B - Determine code output
What This Tests: This question tests ability to trace through multiple ArrayList operations including add at index, set, remove, and get. Each operation changes the list state.

Step-by-Step Trace

// Step-by-step trace:

data.add(10);           // [10]
data.add(20);           // [10, 20]
data.add(30);           // [10, 20, 30]

data.add(1, 15);        // Insert 15 at index 1
                        // [10, 15, 20, 30]
                        // (20 and 30 shift right)

data.set(2, 25);        // Replace index 2 with 25
                        // [10, 15, 25, 30]
                        // (20 becomes 25, no shifting)

data.remove(0);         // Remove index 0
                        // [15, 25, 30]
                        // (10 removed, everything shifts left)

data.add(data.get(0));  // get(0) returns 15
                        // add(15) appends to end
                        // [15, 25, 30, 15]

// Final output: [15, 25, 30, 15]

Key Concept

add(index, elem): Inserts at index, shifts elements at and after that index to the right. Size increases by 1.

set(index, elem): Replaces the element at index. No shifting occurs. Size stays the same.

remove(index): Removes element at index, shifts elements after it to the left. Size decreases by 1.

get(index): Returns element at index without modifying the list.

Common Mistakes

Mistake: Answer B - Forgetting set() replaces, not inserts

set(2, 25) REPLACES index 2 (which is 20 after the add(1,15)). It does not shift anything. The 20 becomes 25.

Mistake: Answer C - Forgetting remove() shifts elements

After remove(0), the element at index 0 (which was 10) is gone, and 15 shifts to become the new index 0.

Mistake: Answer D - Miscalculating get(0) after remove

After remove(0), the list is [15, 25, 30]. So get(0) returns 15, not 25.

AP Exam Tip

Trace ArrayList problems step by step on paper. Write out the full list after EACH operation. Pay special attention to add(index) and remove(index) which cause shifting.

Want More Practice?

Master AP CSA with guided practice and expert help

Schedule 1-on-1 Tutoring Practice FRQs
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.