ExerciseDifficulty: Advanced1 min

Practice: Choosing a List or Deque for Four Access Patterns

Appending, working at both ends, reading by index and removing in bulk: pick a class and name the cost.

The right list depends on the operation done most: positional reads and appends favour ArrayList, work at both ends favours ArrayDeque. For each workload below, choose a class, a list or a deque (a queue you can use from both ends), and say what the alternative would have cost, all four before you open the answer.

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 orders, then remove every cancelled one
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 becomes quadratic
4ArrayList with removeIfOne pass, each element moved at most onceRemoving one at a time in a loop shifts the tail every time

The fourth is the one to pause on, because the answer is not a different class. Removing matches one at a time in a loop is quadratic on both lists; removeIf makes it linear on either.