Skip to content

Make Key record defensively copy its array#154

Open
adamw7 wants to merge 1 commit into
mainfrom
claude/fix-key-defensive-copy
Open

Make Key record defensively copy its array#154
adamw7 wants to merge 1 commit into
mainfrom
claude/fix-key-defensive-copy

Conversation

@adamw7
Copy link
Copy Markdown
Owner

@adamw7 adamw7 commented Apr 19, 2026

Summary

record Key(String[] values) let the caller keep a reference to the array passed into the constructor, and the synthesized accessor handed back the internal reference. Because equals/hashCode are computed from that array via Arrays.equals / Arrays.hashCode, any later mutation of the caller's or returned array silently corrupts Key instances stored in a Set or used as a Map key.

Add a compact constructor and an accessor override that clone the array so the record is effectively immutable.

Also switch equals to instanceof pattern-matching — same behaviour, less boilerplate.

Test plan

  • mvn -pl data test passes (UniquenessCheckTest exercises Key indirectly)
  • Add a regression test: put a Key in a HashSet, mutate the original array, verify set.contains(key) still returns true

record Key(String[] values) exposed its internal array both on the way
in (caller keeps a reference) and on the way out (the synthesized
accessor returns the internal reference). Mutating the array after
construction changes Arrays.hashCode(values) and Arrays.equals(values,
other.values) — which silently corrupts any Set<Key> or Map<Key, ?>
the record was stored in.

Add a compact constructor and accessor override that clone the array.
Also tighten equals to use instanceof pattern matching (equivalent to
the previous class-check path).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants