ArrayList
Traversals
Master the art of iterating through ArrayLists using for loops, enhanced for loops, and while loops: the foundation of data processing in Java.
What Is an ArrayList?
An ArrayList is a resizable, ordered collection of object references in Java. Unlike arrays, ArrayLists can grow and shrink dynamically as elements are added or removed.
Why Traversals Matter
A traversal visits every element in a collection, one at a time. Nearly every real-world task: searching, filtering, summing, or transforming data: requires a traversal.
Three Loop Patterns
Java provides three common ways to traverse an ArrayList. Each has strengths and trade-offs.
The Standard for Loop
The Enhanced for-each Loop
Traversal with a while Loop
for vs for-each: When to Use Each
| Standard for | Enhanced for-each | |
|---|---|---|
| Access index? | ✓ Yes | ✕ No |
| Modify elements? | ✓ via set() | ✕ Read-only |
| Remove elements? | ✓ via remove() | ✕ Throws exception |
| Traverse backwards? | ✓ Yes | ✕ No |
| Cleaner syntax? | ✕ More verbose | ✓ Yes |
How to Write a Traversal
\(0\), end at \(\text{size}() - 1\). Use \(<\), never \(\le\).Example 1: Sum All Values
Given ArrayList<Integer> nums containing [3, 7, 2, 9, 1], compute the total sum.
Example 2: Removing Elements
Remove all even numbers from ArrayList<Integer> nums. This requires an index because we're modifying the list.
Example 3: Backwards Removal
An alternative approach: traverse backwards. Removing an element only shifts elements after the removed index, so earlier indices are unaffected.
Example 4: Linear Search
Find the index of the first occurrence of a target value. Return -1 if not found.
Traversal Decision Flowchart
Common Mistakes
\(i \le \text{list.size}()\) causes an IndexOutOfBoundsException. Always use \(<\).\(i\) after \(\text{remove}(i)\) in a forward loop skips the next element.== instead of .equals() compares references, not values. Almost always wrong.Traversal Summary
| Pattern | Best For | Key Syntax |
|---|---|---|
| Standard for | Index access, modify, remove | for (int i = 0; ...) |
| Enhanced for-each | Read-only traversal | for (T x : list) |
| While loop | Conditional removal, flexible stop | while (i < size()) |
| Backwards for | Clean removal without skip | for (i = size()-1; ...) |
Question 1 of 5
What is the output of the following code?
ArrayList<Integer> nums = new ArrayList<>();
nums.add(10); nums.add(20); nums.add(30);
for (int i = 0; i < nums.size(); i++) {
System.out.print(nums.get(i) + " ");
}
size() is 3), printing each element: 10 20 30.Question 2 of 5
Which loop type should you use to remove elements from an ArrayList during traversal?
ConcurrentModificationException. A forward for with \(i++\) skips elements. Use a while loop (don't increment on remove) or a backwards for loop.Question 3 of 5
What happens when this code executes?
ArrayList<String> words = new ArrayList<>();
words.add("Hi"); words.add("Bye");
for (String w : words) {
if (w.equals("Hi")) {
words.remove(w);
}
}
ConcurrentModificationException. Use a standard for or while loop instead.Question 4 of 5
Given ArrayList<Integer> a with values [4, 7, 4, 2, 4], how many elements remain after this code runs?
for (int i = a.size() - 1; i >= 0; i--) {
if (a.get(i) == 4) {
a.remove(i);
}
}
Question 5 of 5
What is the value of count after this code runs on the list ["apple", "banana", "avocado", "cherry", "apricot"]?
int count = 0;
for (String s : list) {
if (s.substring(0, 1).equals("a")) {
count++;
}
}