JavaMedium

The set that will not deduplicate

An import job reads orders from a feed that repeats rows, and drops them into a HashSet to deduplicate. Two orders are the same order when their reference matches.

The set is full of duplicates. equals() was written and reviewed and is correct. Make the deduplication work.

Example

inputthree OrderRef values, two of them equaloutputa set of size 2

Logical equality, not identity: two separately constructed refs with the same value are one order.

Constraints

  • Do not change what equals() considers equal.
  • A HashMap keyed by the same type must find a value put under a logically equal key.
  • Objects that are equal must stay equal after being read back out of a collection.

Hints

Hint 1
A HashSet does not call equals() on everything it holds. It calls it on the things in one bucket.
Hint 2
Which bucket an object lands in is decided by hashCode(), and Object's hashCode is identity-based — two equal refs land in different buckets and never meet.
Hint 3
The contract is one-directional: equal objects MUST have equal hash codes. Unequal objects may share one.

Stuck? The lesson behind this problem: 🗂️ HashMap internals

java
Tab indents · Escape first to tab out

Test cases

These are the specification. Run tests checks your answer against them.

CaseInputExpected
duplicates collapse in a setsize = 2
a map finds a value under an equal keyfound
unequal refs stay distinctsize = 3
equal refs agree on their hashtrue