Part 3 · Fundamentals

Collections, generics and equality

Prerequisites: 01-ecosystem

Which collection matches the invariant?

Requirement: What must stay true?; List: sequence + duplicates; Set: unique membership; Map: key → value. Connections: Requirement to List (ordered sequence); Requirement to Set (uniqueness); Requirement to Map (lookup by key)
These are contracts, not performance rankings. Implementation and workload determine cost. [S06] [S07] [S05]

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]
Keep this: Collection contracts are part of your domain contract.
Check yourself: Why are mutable map keys dangerous?

Their hash/equality behavior may change after storage, so later lookup searches the wrong location.

Sources & further reading

  1. [S05] Object equality and hashing

    Oracle / OpenJDK · documentation · accessed 2026-10-09 · Java SE 25

    Supports: equals/hashCode contract

    Read the linked section to validate the mechanism and its version-specific constraints.

  2. [S06] Collections package

    Oracle / OpenJDK · documentation · accessed 2026-10-09 · Java SE 25

    Supports: Collection roles and implementations

    Read the linked section to validate the mechanism and its version-specific constraints.

  3. [S07] HashMap API

    Oracle / OpenJDK · documentation · accessed 2026-10-09 · Java SE 25

    Supports: HashMap behavior and ordering limits

    Read the linked section to validate the mechanism and its version-specific constraints.