Collections, generics and equality
Prerequisites: 01-ecosystem
Which collection matches the invariant?
Goal & mental model verified
Select the collection by its contract: List preserves a sequence, Set models uniqueness, Map associates keys and values. Hash-based containers rely on equality and hashing; HashMap does not promise iteration order.
[S06] [S07]Worked example · design exercise synthesis
A broker list preserves display order; a Set tracks unique coverage codes; a Map indexes quotes by stable QuoteId. Use a sorted map when sorted traversal is part of the requirement.
[S06] [S07] [S05]Engineering decision synthesis
Prefer interface-typed variables and explicit generic parameters. Choose ArrayList for ordinary indexed sequences; choose a deque for queue/stack operations instead of treating one structure as universal.
[S06] [S07] [S05]Pitfall & diagnosis synthesis
Changing fields used by a key’s equality/hash after insertion can make lookup fail. Concurrent access needs a suitable concurrency strategy, not merely a different collection name.
[S06] [S07] [S05]Improve & validate synthesis
Write down ordering, duplicate and mutation requirements before selection. Measure realistic access patterns before swapping structures for supposed performance gains.
[S06] [S07] [S05]Check yourself: Why are mutable map keys dangerous?
Their hash/equality behavior may change after storage, so later lookup searches the wrong location.