01 / 21

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.

AP Computer Science A

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.

index 0 1 2 3 4 "Cat" "Dog" "Bee" "Fox" "Owl" size() = 5 ArrayList<String>

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.

Search
Find a specific value in a list of students
Filter
Remove all items that fail a condition
Transform
Convert every String to uppercase

Three Loop Patterns

Java provides three common ways to traverse an ArrayList. Each has strengths and trade-offs.

for loop
Index-based access. Full control over start, end, and step.
for-each loop
Cleaner syntax. Reads every element automatically.
while loop
Flexible condition. Useful when the stop point is unknown.

The Standard for Loop

for (int i = 0; i < list.size(); i++) { String elem = list.get(i); System.out.println(elem); }

The Enhanced for-each Loop

for (String elem : list) { System.out.println(elem); }

Traversal with a while Loop

int i = 0; while (i < list.size()) { System.out.println(list.get(i)); i++; }

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

1
Identify your goal: Are you reading, modifying, removing, or counting elements?
2
Choose the loop type: Read-only → for-each. Need index → standard for. Removing → while or backwards for.
3
Set bounds carefully: Start at \(0\), end at \(\text{size}() - 1\). Use \(<\), never \(\le\).
4
Process each element: Apply your logic inside the loop body.
5
Handle edge cases: What if the list is empty? What if every element matches?

Example 1: Sum All Values

Given ArrayList<Integer> nums containing [3, 7, 2, 9, 1], compute the total sum.

int sum = 0; for (int n : nums) { sum += n; } System.out.println(sum); // 22
3 7 2 9 1 +3 +7 +2 +9 +1 3 10 12 21 22 ← sum

Example 2: Removing Elements

Remove all even numbers from ArrayList<Integer> nums. This requires an index because we're modifying the list.

int i = 0; while (i < nums.size()) { if (nums.get(i) % 2 == 0) { nums.remove(i); // Do NOT increment i } else { i++; } }

Example 3: Backwards Removal

An alternative approach: traverse backwards. Removing an element only shifts elements after the removed index, so earlier indices are unaffected.

for (int i = nums.size() - 1; i >= 0; i--) { if (nums.get(i) % 2 == 0) { nums.remove(i); } }
Traversal direction ← 3 8 5 2 7 Result: 3 5 7

Example 4: Linear Search

Find the index of the first occurrence of a target value. Return -1 if not found.

public static int search(ArrayList<String> list, String target) { for (int i = 0; i < list.size(); i++) { if (list.get(i).equals(target)) { return i; } } return -1; }

Traversal Decision Flowchart

Need to traverse? Need index or modifying? Yes No for-each Removing? Yes No Standard for Direction? Backward Forward for loop i = size()-1 while loop skip i++

Common Mistakes

✕ Off-by-one with ≤
Using \(i \le \text{list.size}()\) causes an IndexOutOfBoundsException. Always use \(<\).
✕ Skipping after remove
Incrementing \(i\) after \(\text{remove}(i)\) in a forward loop skips the next element.
✕ Using == for Strings
Using == instead of .equals() compares references, not values. Almost always wrong.
✕ Modifying in for-each
Adding or removing elements during a for-each loop throws a ConcurrentModificationException.

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?

Question 2 of 5

Which loop type should you use to remove elements from an ArrayList during traversal?

Question 3 of 5

What happens when this code executes?

Question 4 of 5

Given ArrayList<Integer> a with values [4, 7, 4, 2, 4], how many elements remain after this code runs?

Question 5 of 5

What is the value of count after this code runs on the list ["apple", "banana", "avocado", "cherry", "apricot"]?