AP® Computer Science A · Unit 4 · Topic 4.9
Traversing an ArrayList
Traversing an ArrayList means visiting every element with a loop, using list.size() instead of .length and list.get(i) instead of square brackets.
An ArrayList traversal looks almost like an array traversal because the idea is identical: start at index 0, visit each index in turn, stop after the last one. But ArrayList is a class, not a built-in array, so it swaps array syntax for method calls. Where an array gives you arr.length, an ArrayList gives you list.size(), a method call with parentheses. Where an array lets you read arr[i], an ArrayList makes you call list.get(i). Same job, different tools, because size() and get() are ordinary methods defined inside the ArrayList class rather than language features built into array syntax.
The loop condition is where most mistakes happen. Valid indexes run from 0 to size() - 1, since size() returns the count of elements, not the last index. A loop written as for (int i = 0; i ≤ list.size(); i++) runs one pass too many: on that last pass i equals size() itself, which is one past the final valid index, and list.get(i) throws IndexOutOfBoundsException. The safe condition is i < list.size().
Once you can traverse, you can accumulate: summing, searching, counting, or building a new list by reading one element per pass and updating a running result. This sets up everything else in the unit, since searching and sorting algorithms are really just traversals with extra logic layered on. The enhanced for loop, for (int x : list), removes the index entirely and hands you each element directly, which is cleaner when you only need to read values and never need i itself, but it cannot be used to set elements or track position.
Key terms
- size()
- A method that returns the number of elements currently stored in an ArrayList.
- get(i)
- A method that returns the element stored at index i in an ArrayList.
- IndexOutOfBoundsException
- An error thrown when code tries to access an index that does not exist in the list.
- enhanced for loop
- A loop of the form for (type x : list) that visits each element in order without using an index.
Watch it explained
- How it worksHow does size replace length and get(i) replace the square brackets?
- Worked exampleTrace a loop that sums an ArrayList holding 4, 11, 6 and find the total each pass.
- Worked exampleFind where a loop testing i ≤ list.size() throws IndexOutOfBoundsException.
- Going furtherWhat changes when an enhanced for loop is used on an ArrayList instead?
Check yourself
End of topic.