ExerciseDifficulty: Advanced1 min

Four Access Patterns: Choose a List and Say What It Costs

Four workloads. For each, choose a list and say what the alternative would have cost. Write all four down before opening the reveal.

The four workloads
The workload
1Read a million rows from a file, appending each, then walk them once
2Keep the fifty most recent events, adding at the front and dropping from the end
3A lookup table of ten thousand rows, read by index inside a tight loop
4Build a list of a hundred thousand, then remove every third element by index
The four choices, and what the other option would have cost
Each workload, the choice, and the alternative's cost
ChooseBecauseThe alternative costs
1ArrayList, sized aheadAppend and walk are both its best caseLinkedList adds two pointers per element for no gain
2ArrayDequeConstant at both ends, with no per-element pointersLinkedList also works; ArrayList shifts fifty elements per add
3ArrayListPositional reads are arithmeticLinkedList turns each read into a walk, so the loop goes quadratic
4ArrayList with removeIfOne pass, each element moved at most onceRemoving by index in a loop shifts the tail each time

The fourth is the one worth pausing on, because the answer is not a different class. Removing by index in a loop is quadratic on an array list and quadratic on a linked one — removeIf is what makes it linear on either.