AP Computer Science A: Lesson 4.9

Traversing ArrayLists

Unit 4: Data Collections

This notebook serves as a complete lesson plan, presentation guide, code sandbox, and homework assignment for Topic 4.9.


🖥️ Presentation & Slide Deck

Slide 1: ArrayLists vs. Static Arrays

  • Title: Dynamic Traversal with ArrayList
  • Key Differences: Dynamic sizing via .size(), element retrieval via .get(i), and element removal via .remove(i).
  • Traversal Choices: Standard indexed for loop vs. Enhanced for-each loop.

🗣️ Teacher Script:

“When working with dynamic lists, modifying the size while traversing creates major bugs if you aren’t careful. Today we master the famous Index-Shifting Trap!”

Slide 2: The Index-Shifting Bug

Goal: Remove all even numbers from [4, 2, 8, 3, 6].

Flawed Forward Loop:

// Flawed Removal Loop
import java.util.ArrayList;
import java.util.Arrays;

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(4, 2, 8, 3, 6));
for (int i = 0; i < list.size(); i++) {
    if (list.get(i) % 2 == 0) {
        list.remove(i); // Elements shift left, skipping adjacent elements!
    }
}

🗣️ Teacher Script:

“Trace this carefully: When index 0 (4) is removed, 2 shifts down to index 0. But the loop increments i to 1, looking at index 1 (8). 2 was completely skipped! To avoid this, we traverse backwards from list.size() - 1 down to 0.”

Slide 3: The Backward Traversal Solution

// Correct Backward Traversal
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(4, 2, 8, 3, 6));

for (int i = list.size() - 1; i >= 0; i--) {
    if (list.get(i) % 2 == 0) {
        list.remove(i); // Index shifts only affect already-processed elements!
    }
}
// Resulting list: [3]


📄 Student Homework Assignment Handout

Title: Vocabulary Filter Sandbox

Instructions:

  1. Complete the removeShortWords method below using a backward traversal.
  2. Answer the reflection question on ConcurrentModificationException.
import java.util.ArrayList;

public class WordFilter {

    /**
     * Removes all words with fewer than 4 characters from the list.
     * Uses backward loop traversal.
     */
    public static void removeShortWords(ArrayList<String> words) {
        for (int i = words.size() - 1; i >= 0; i--) {
            if (words.get(i).length() < 4) {
                words.remove(i);
            }
        }
    }
}

Short Answer Reflection

Question: Why does using an enhanced for loop (for (String w : words)) throw a ConcurrentModificationException when attempting to call words.remove(w) inside the loop?

Your Answer: (Explain the structural modification rule of enhanced for-each loops in Java)