4.09 Transversing ArrayLists
Traverse ArrayLists with index-based and enhanced for loops while safely accessing and updating collection elements.
- AP Computer Science A: Lesson 4.9
- Traversing ArrayLists
- π₯οΈ Presentation & Slide Deck
- Slide 1: ArrayLists vs. Static Arrays
- Slide 2: The Index-Shifting Bug
- Code Runner Challenge
- Slide 3: The Backward Traversal Solution
- Code Runner Challenge
- π Student Homework Assignment Handout
- Code Runner Challenge
- Short Answer Reflection
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
forloop vs. Enhancedfor-eachloop.
π£οΈ 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:
Code Runner Challenge
Predict what is left after removing the even numbers, then run it and find which numbers were skipped
View IPYNB Source
// CODE_RUNNER: Predict what is left after removing the even numbers, then run it and find which numbers were skipped
import java.util.ArrayList;
import java.util.Arrays;
public class FlawedRemoval {
public static void main(String[] args) {
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!
}
}
System.out.println(list); // Should be [3]. Is it?
}
}
FlawedRemoval.main(null);
π£οΈ Teacher Script:
βTrace this carefully: When index 0 (
4) is removed,2shifts down to index 0. But the loop incrementsito 1, looking at index 1 (8).2was completely skipped! To avoid this, we traverse backwards fromlist.size() - 1down to0.β
Slide 3: The Backward Traversal Solution
Code Runner Challenge
Run it and compare the result with the forward loop above
View IPYNB Source
// CODE_RUNNER: Run it and compare the result with the forward loop above
import java.util.ArrayList;
import java.util.Arrays;
public class BackwardRemoval {
public static void main(String[] args) {
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!
}
}
System.out.println(list); // Resulting list: [3]
}
}
BackwardRemoval.main(null);
π Student Homework Assignment Handout
Title: Vocabulary Filter Sandbox
Instructions:
- Complete the
removeShortWordsmethod below using a backward traversal. - Answer the reflection question on
ConcurrentModificationException.
Code Runner Challenge
Finish removeShortWords with a backward loop so all three checks print true
View IPYNB Source
// CODE_RUNNER: Finish removeShortWords with a backward loop so all three checks print true
import java.util.ArrayList;
import java.util.Arrays;
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) {
// TODO: loop from the last index down to 0 and remove words shorter than 4 characters
}
public static void main(String[] args) {
ArrayList<String> words = new ArrayList<>(Arrays.asList("the", "cat", "jumped", "over", "a", "lazy", "dog"));
removeShortWords(words);
System.out.println(words);
System.out.println(words.equals(Arrays.asList("jumped", "over", "lazy")));
// Two short words next to each other: a forward loop skips the second one.
ArrayList<String> pairs = new ArrayList<>(Arrays.asList("an", "it", "java"));
removeShortWords(pairs);
System.out.println(pairs.equals(Arrays.asList("java")));
ArrayList<String> empty = new ArrayList<>();
removeShortWords(empty);
System.out.println(empty.isEmpty());
}
}
WordFilter.main(null);
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)
Submit Assignment
Need to update a submission later? Open the submissions dashboard.