From the free course AP Computer Science A on Lykke

4.9 ArrayList Traversals

Key concepts: ArrayList traversals

An ArrayList traversal visits the elements of an ArrayList in sequence so that a program can inspect, display, compare, or process each stored object. The central question is simple: How can a program examine every element without knowing the list’s contents in advance?

4.9 ArrayList Traversals

An ArrayList traversal visits the elements of an ArrayList in sequence so that a program can inspect, display, compare, or process each stored object. The central question is simple: How can a program examine every element without knowing the list’s contents in advance?

The traversal pattern

An ArrayList stores elements at indexes beginning with $0$ and ending with `list.size() - 1$. A traversal therefore needs a reliable way to move from the first valid index to the last valid index.

A traditional for loop exposes the index, while an enhanced for loop directly provides each element:

for (int index = 0; index < names.size(); index++) {
    System.out.println(names.get(index));
}

for (String name : names) {
    System.out.println(name);
}

Both loops visit the elements in order. If names contains ["Ari", "Bea", "Chen"], each loop produces Ari, then Bea, then Chen. The first loop uses names.get(index); the enhanced for loop assigns each visited element to name.

CED alignment — 4.9.A: Traverse the elements of an ArrayList.
Essential Knowledge 4.9.A.1: An ArrayList can be traversed using an index-based for loop or an enhanced for loop.

Choosing the right loop

Use an index-based loop when the position matters or when the program must replace an element. Use an enhanced for loop when the program only needs to read or process each element.

Goal Suitable traversal Reason
Print every element Enhanced for loop The index is unnecessary
Compare adjacent elements Index-based for loop The current and neighboring indexes matter
Replace elements Index-based for loop set(index, value) requires an index
Count elements meeting a condition Either loop Each element can be tested directly

Worked example: finding a temperature threshold

Suppose a weather station stores daily temperatures in an ArrayList<Integer>. The program should count how many readings are at least $30$ degrees.

ArrayList<Integer> temperatures =
    new ArrayList<Integer>();

temperatures.add(27);
temperatures.add(31);
temperatures.add(30);
temperatures.add(24);

int hotDays = 0;

for (int temperature : temperatures) {
    if (temperature >= 30) {
        hotDays++;
    }
}

System.out.println(hotDays);

The traversal visits $27$, $31$, $30$, and $24$. The condition is true for $31$ and $30$, so hotDays becomes $2$. Notice that the loop does not alter the ArrayList; it only reads each element and updates a separate accumulator.

Index boundaries and mutation

The most common index-based pattern is:

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

The condition must use i < values.size(), not i <= values.size(). If the list has $4$ elements, its valid indexes are $0$, $1$, $2$, and $3$; index $4$ is outside the list and causes an IndexOutOfBoundsException`.

A traversal that changes list size is especially dangerous. Removing an element while moving forward causes later elements to shift left, so the next index may skip an element. A traversal may safely use set when the list size remains unchanged, but adding or removing elements requires a carefully designed algorithm.

Misconception check

Misconception: “The enhanced for loop variable is the list element’s permanent storage location.” The variable receives the current reference or value; assigning a new value to that variable does not replace the element in the list.

for (String item : items) {
    item = item.toUpperCase();   // does not update items
}

To replace elements, use an index:

for (int i = 0; i < items.size(); i++) {
    items.set(i, items.get(i).toUpperCase());
}

For object elements, changing the object through its reference can affect the object stored in the list, but reassigning the loop variable does not change which reference the list stores. This distinction is essential when tracing ArrayList code.

AP skill connections

ArrayList traversals develop Computational Thinking Practice 2 — Develop Code, because the programmer implements a loop that performs required functionality; Computational Thinking Practice 3 — Analyze Code, because the programmer traces indexes, conditions, and list contents; and Computational Thinking Practice 4 — Document Code and Computing Systems, because comments and method documentation can state traversal assumptions such as valid index ranges. In particular, tracing a traversal means tracking both the loop variable and the changing accumulator after every iteration.

Retrieval check

A list contains ["red", "blue", "green"]. What happens in this loop?

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

It prints the three valid elements, then attempts colors.get(3) and throws an IndexOutOfBoundsException. Replace <= with < to visit every element exactly once.

4.9 ArrayList Traversals - AP Computer Science A - image 1
4.9 ArrayList Traversals - AP Computer Science A - image 1
4.9 ArrayList Traversals - AP Computer Science A - diagram 1
4.9 ArrayList Traversals - AP Computer Science A - diagram 1

Source Materials

The whole course on Lykke · Browse all public course wikis