Topic 4.6 — Traversing ArrayLists
Goal: traverse an ArrayList using indexed loops, use size() correctly,
and handle modification patterns safely.
The big idea
Traversing an ArrayList looks a lot like traversing an array—but you use
size() and get(i) instead of length and [i].
If you’re reading or updating by index, an indexed for loop is your best friend.
Canonical traversal loop (memorize)
for (int i = 0; i < list.size(); i++) {
// use list.get(i)
}
- Indexes run from
0tolist.size() - 1 - Don’t write
i <= list.size()(off-by-one)
Example: sum values in an ArrayList<Integer>
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums.get(i);
}
This is the ArrayList version of the classic “accumulator” pattern.
Example: replace values using set
Update elements in-place by index.
// Replace negatives with 0
for (int i = 0; i < nums.size(); i++) {
if (nums.get(i) < 0) {
nums.set(i, 0);
}
}
Find max (value + index)
Track the index where the best value lives.
int maxIndex = 0;
for (int i = 1; i < nums.size(); i++) {
if (nums.get(i) > nums.get(maxIndex)) {
maxIndex = i;
}
}
Modification warning: removing while traversing
Removing shifts elements left, so you can accidentally skip items if you go forward.
// ❌ Risky: may skip elements after a remove
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 0) {
list.remove(i);
}
}
Safe remove pattern: go backward
Traversing from the end avoids skipping because indexes after i don’t shift “past” you.
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i) == 0) {
list.remove(i);
}
}
Common mistakes
| Mistake | Why it’s wrong | Fix |
|---|---|---|
list.length |
ArrayLists don’t have length |
Use list.size() |
list[i] |
ArrayLists don’t use bracket indexing | Use list.get(i) |
i <= list.size() |
Last valid index is size()-1 |
Use i < list.size() |
| Remove while looping forward | Shifts elements; may skip checks | Loop backward or adjust index |
Quick self-check
- What’s the correct loop condition for traversing:
i < list.size()ori <= list.size()? - How do you read the element at index 3?
- How do you replace the element at index 3?
- Why is removing while looping forward risky?
- Write a backward loop that removes all zeros.