AP® Computer Science A · Unit 4 · Topic 4.10
Standard ArrayList Algorithms
A small set of loop patterns over an ArrayList — traverse, compare, accumulate — solves almost every list problem, from summing values to finding duplicates or shifting elements.
Nearly every ArrayList algorithm starts the same way: a for loop that walks through indices 0 to size() - 1, looking at one element per pass. What changes is what you do with each element and what you carry forward. To sum a list, you add each element into a running total. To count matches, you add one to a counter when a condition is true. To find a maximum, you keep a variable holding the best value seen so far and update it when you find something bigger. To search, you compare each element to a target and stop early — or report true — the moment you find it. Same shape, different job.
Some problems need two traversals working together. A duplicate check compares every pair of elements: an outer loop picks one index, an inner loop checks every other index against it, and a match anywhere means the list has a duplicate. A left-shift algorithm reads from one index and writes to the index before it, moving every element down by one and shrinking the usable list by one slot — the first element gets overwritten and effectively dropped.
The real shift in this unit is what the loop returns. Sum, count, and maximum all end with one number. But algorithms can instead build a new ArrayList: traverse the original, test each element, and add the ones that pass to a result list. That single change — accumulating a collection instead of a single value — is the bridge from basic traversal to filtering, copying, and the searching and sorting algorithms that follow.
Key terms
- Traversal
- A loop that visits every element of a list exactly once, usually by index.
- Accumulator
- A variable that carries a running result, like a total or count, across loop iterations.
- Pairwise comparison
- Checking every element against every other element, often with a nested loop, to find matches like duplicates.
- Early termination
- Stopping a loop as soon as the answer is known, such as returning true the moment a search finds its target.
Watch it explained
- How it worksHow does one traversal pattern get reused for sum, count, maximum, and search?
- Worked exampleFind whether the list 3, 9, 3, 5 holds any duplicate values, checking pair by pair.
- Worked exampleTrace a loop that shifts every element of a list left by one and drops the first.
- Going furtherWhat changes when the algorithm must return elements rather than one single number?
Check yourself
End of topic.