AP® Computer Science A · Unit 4 · Topic 4.10

Traversing Two Collections at Once

When two collections store related data at matching positions, you walk them with a single shared index so each step compares or combines the pair at that position.

Some problems need two collections read together, not one at a time. If names[i] and scores[i] describe the same person, you don't want two separate loops — you want one index i that steps through both arrays at once, so each iteration gives you a matched pair. The loop counter does double duty: it's a position in names and the same position in scores, simultaneously.

The mechanism is just a single for loop: for (int i = 0; i < length; i++), and inside it you reference both collections with that same i — names.get(i) alongside scores.get(i), or names[i] alongside scores[i]. To find the top scorer, track a running maximum and the index where it occurred, updating both whenever scores[i] beats the current best. To check if two arrays are equal, walk both with one i and compare array1[i] to array2[i] at every step, stopping and returning false the moment a mismatch shows up; if the loop finishes with no mismatches, they're equal.

This builds directly on single-collection traversal from earlier in the unit — same shifting-index idea, just driving two collections instead of one. It also sets up more complex multi-structure work later, like comparing rows of a 2D array or merging two sorted lists, where keeping indices aligned (or handling them when they can't stay aligned) becomes the whole problem.

Key terms

Lockstep traversal
Walking two collections together using one shared index so corresponding positions line up each iteration.
Shared index
A single loop counter variable used to access the same position in two different collections at once.
ArrayIndexOutOfBoundsException
The runtime error thrown when code accesses an array position at or beyond its length.
Loop bound
The value a loop counter is compared against to decide when to stop, which must match the shorter collection's length here.

Watch it explained

  1. How it worksHow does a single loop counter walk two collections in lockstep?
  2. Worked exampleTrace matching names to scores across two lists of length 4 to find the top scorer.
  3. Worked exampleFind whether {1, 2, 3} and {1, 2, 4} are equal by walking both arrays at once.
  4. Going furtherWhat changes when the two collections turn out to have different lengths?

Check yourself

Your turn1 of 2
Two lists, names and scores, are walked in lockstep by one shared index. At index i, the score is 70; at a different index j, the score is 65. Using just these two scores, what is the higher of the two?

End of topic.