Unit 4 Day 21 Arraylist Comprehensive
Share
Practice Question
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);
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
set(2, 25) REPLACES index 2 (which is 20 after the add(1,15)). It does not shift anything. The 20 becomes 25.
After remove(0), the element at index 0 (which was 10) is gone, and 15 shifts to become the new index 0.
After remove(0), the list is [15, 25, 30]. So get(0) returns 15, not 25.
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