Unit 4 Day 19 Arraylist Shifting
Share
Practice Question
public static void insertEveryOther(ArrayList<String> list, String val)
{
// Intended: insert val at indices 0, 2, 4, 6, ...
for (int i = 0; i < list.size(); i += 2)
{
list.add(i, val);
}
}
// Test:
ArrayList<String> words = new ArrayList<>();
words.add("A"); words.add("B"); words.add("C");
insertEveryOther(words, "X");
// Expected: [X, A, X, B, X, C]
Step-by-Step Trace
// Initial: [A, B, C], size = 3
// i=0: add("X" at 0), list = [X, A, B, C], size = 4
// i=2: add("X" at 2), list = [X, A, X, B, C], size = 5
// i=4: add("X" at 4), list = [X, A, X, B, X, C], size = 6
// i=6: 6 < 6? NO... wait, size is now 6!
// i=6: add("X" at 6), list grows to size 7
// i=8: 8 < 7? NO... but we just added, now size = 7
// Actually: Every insertion increases size()
// i always catches up: 0<3, 2<4, 4<5, 6<6? NO
// But wait: after i=4 insert, size=6, then i=6, 6<6 is FALSE
// Let me retrace more carefully:
// i=0: 0<3? YES, insert, size=4
// i=2: 2<4? YES, insert, size=5
// i=4: 4<5? YES, insert, size=6
// i=6: 6<6? NO, loop ends
// WAIT - rechecking: i increments by 2 each time
// But size increases by 1 each insertion
// So i gains 2, size gains 1 = i will eventually exceed
// NOT infinite... let me reconsider the trace
// Actually with small list, terminates. With larger list
// or if i += 1, it would be infinite.
// The key bug: list keeps growing, loop runs longer than expected
Key Concept
The Shifting Problem: When you call add(index, element), the ArrayList size increases by 1. If your loop condition is i < list.size(), the target keeps moving.
This specific case: Since i increases by 2 but size only increases by 1, the loop eventually terminates but with wrong results. If i += 1, it would be truly infinite.
Fix: Store the original size before the loop, or iterate backward, or calculate exact insertion points ahead of time.
Common Mistakes
Each insertion shifts elements AND increases size. The loop condition i < list.size() uses the NEW size each iteration, causing more iterations than intended.
Trace through carefully: after inserting at 0, element "A" moves to index 1. After inserting at 2, the original "B" (now at index 3) shifts further. The final positions are wrong.
When adding elements during a loop, the list size changes! Either save the original size in a variable before the loop, or use backward traversal. AP exam questions love this trap.
Want More Practice?
Master AP CSA with guided practice and expert help
Schedule 1-on-1 Tutoring Practice FRQs