Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Your platform team maintains shared libraries used by many services, and several incidents came from key classes with bad equals and hashCode. What conventions for value objects used as map keys or cache keys would you set across teams, and how would you enforce them?

I would set four conventions: keys are records or immutable classes with final identity fields; JPA entities and other mutable objects are never keys in long-lived maps or caches; equals and hashCode are generated or derived, never hand-written partially, and are covered by contract tests such as EqualsVerifier; and every key type defines a canonical form, such as normalised case or BigDecimal scale, before it is built. Enforcement comes from a shared review checklist, static analysis such as Error Prone and ArchUnit rules in the shared build, and contract tests that fail the build rather than relying on memory.

Why this question is asked

When a key class has a broken equals or hashCode, the symptoms appear far from the cause: a cache that never hits, a map that loses entries, a Set with duplicates, or a lookup path that slows down tenfold. In a platform team, a bad key in a shared library is copied into dozens of services before anyone notices. Interviewers ask this design question to see whether a senior engineer can turn scattered incidents into a few clear rules, explain the reasons behind them, and make them stick without policing every pull request by hand. In this answer, we will look at the failure modes the rules must prevent, set out each convention with its reason, show what a compliant key looks like, and then decide how to enforce the rules across teams.

1The Failure Modes Behind the Incidents

Almost every key incident falls into one of four groups. The first is inconsistency: equals and hashCode disagree, for example equals compares three fields and hashCode uses two plus a field that equals ignores, so equal keys land in different buckets. The second is mutation: a field used by hashCode changes while the key sits in a map, so the entry is stranded in the bucket of its old hash and can no longer be found or removed. The third is weak spreading: a hashCode that uses too few fields, so millions of keys share a few hash values. The fourth is representation: two keys that mean the same thing are built differently, such as "Alice@Example.com" and "alice@example.com", or a BigDecimal amount of 10.0 and 10.00, so they are not equal.

Our conventions should make each of these hard to write by accident, and easy to catch when it happens anyway.

Key failure modes and the convention that prevents each
FailureSymptomConvention
equals and hashCode disagreelookups miss, Set holds duplicatesgenerate both; contract tests
Key mutated while in a mapentry stranded, memory leakrecords or immutable final fields
Hash uses too few fieldslatency jump, crowded binsderive hash from all equals fields
Same meaning, different formcache misses, double entriescanonical form at construction
Entity used as keyhash changes after persistno entities in long-lived maps

2Convention 1: Keys Are Records or Immutable Classes

A record declares its components once, and the compiler generates equals and hashCode from exactly those components. The fields are final, so a record key cannot change after it is put into a map. That single choice removes inconsistency and mutation for the common case. When a record cannot be used, for example because the key must hide a field or extend a framework type, the class must be final, its identity fields final, and any collections inside it copied into unmodifiable ones in the constructor.

The reason the rule talks about identity fields is that some keys carry extra data that does not take part in equality, such as a display label. Those fields should not exist on a key at all; keys should hold only what identifies the thing.

3Convention 2: No Entities or Mutable Objects as Long-Lived Keys

JPA entities are the most common offender. An entity's id is often null until it is persisted, so its hashCode changes at the moment of saving if it is based on the id. Entities are also mutable by design, may be Hibernate proxies of a subclass, and carry lazy associations that can trigger database queries inside equals or hashCode. A cache keyed by an entity is therefore fragile in several ways at once.

The rule is that long-lived maps and caches are keyed by an explicit value, usually a record holding the entity's business key or its id type, such as record CustomerId(long value). Short-lived local maps inside one method are allowed more freedom, but shared libraries should not accept entities as keys in their APIs.

4Convention 3: Derive equals and hashCode, Then Test the Contract

Hand-written equals and hashCode are where partial implementations come from: a field added to the class and to equals but forgotten in hashCode, or an equals(Order other) overload that never overrides equals(Object). We forbid hand-written versions on key types and accept only records, IDE-generated code that is regenerated when fields change, or a library such as Lombok's @EqualsAndHashCode if the organisation already uses it.

Generation still leaves room for mistakes, so we test the contract. EqualsVerifier is a testing library that checks equals and hashCode against the rules, including symmetry, transitivity, null handling, consistency between the two methods and whether mutable fields take part. One line per key class is enough.

Java
record AccountKey(String tenant, String accountNo) {
AccountKey {
tenant = tenant.strip().toLowerCase(Locale.ROOT); // canonical form
accountNo = accountNo.strip();
}
}
@Test
void accountKeyHonoursTheContract() {
EqualsVerifier.forClass(AccountKey.class).verify(); // fails the build if broken
}
new AccountKey(" ACME ", "42").equals(new AccountKey("acme", "42")); // true

Notice the compact constructor. It is the single place where the key's canonical form is applied, which brings us to the next convention.

5Convention 4: Canonical Forms Before Keys Are Built

Two values that mean the same thing must become equal keys. For text, that usually means trimming and choosing a case with an explicit Locale.ROOT, because default-locale lowercasing changes some letters in Turkish locales. For BigDecimal, equals considers scale, so 10.0 and 10.00 are different keys; we normalise with stripTrailingZeros() or a fixed setScale(2) for money. For time, we store Instants or a fixed zone rather than local date-times from different zones.

The convention is that normalisation happens inside the key type, in the constructor or a static factory, never at call sites. If callers must remember to normalise, some will forget, and the cache will hold two entries for one customer.

6Enforcing the Conventions Across Teams

Rules that live only in a document fade. We put them where engineers already work. The shared build gets Error Prone, a compiler plugin from Google, which already flags several equals and hashCode mistakes, such as equals overloads and mismatched implementations, and can fail the build on them. ArchUnit, a library for testing architecture rules as unit tests, can express our own rules, for example that no class annotated with @Entity appears as a key type parameter of fields in cache classes, or that classes named *Key must be records. Sonar or similar analysis adds dashboards across repositories.

Static analysis cannot catch everything, so a short review checklist covers the rest: is this key a record, does it normalise its inputs, is there an EqualsVerifier test. Finally, the shared library itself sets the example. Its own APIs take value-type keys, its cache helpers reject entities at compile time through generics or at startup through a check, and its documentation links each rule to the incident that motivated it, because engineers follow rules they understand.

7Follow-up questions

Why not just tell teams to be careful?

Because the failures are silent. A bad key does not throw; it makes a cache miss or a lookup slow, and the cause is far from the symptom. Rules that are checked automatically scale to many teams, while care does not survive staff changes, deadlines and code generated in a hurry.

Are records always safe as keys?

Only if their components are immutable. A record holding a List gets a hashCode that depends on the list's contents, so mutating that list changes the hash. Records used as keys should hold immutable values, and any collection component should be copied with List.copyOf in the compact constructor.

How would you roll this out to existing code?

Start with the shared libraries and the incident-prone services, add EqualsVerifier tests to existing key classes to find current violations, turn on Error Prone checks as warnings first and errors once the backlog is cleared, and convert keys to records when they are touched for other reasons.

8Conclusion

In this answer, we traced key incidents to four causes, inconsistency, mutation, weak spreading and inconsistent representation, and set conventions against each: records or immutable keys with final identity fields, no entities or mutable objects in long-lived maps and caches, generated equals and hashCode verified by EqualsVerifier, and canonical forms applied inside the key type. We enforced them through Error Prone and ArchUnit in the shared build, a short review checklist, and shared libraries that model the rules themselves.

What to say in the interviewAbout 80 seconds aloud

Open with

I would first group the incidents, because they usually come from four causes: equals and hashCode disagreeing, keys mutated while in a map, hashes built from too few fields, and the same value represented in two forms.

Then, if they want more

Then I would set conventions against each. Keys are records or immutable final classes with final identity fields, so they cannot change after insertion and the compiler derives equals and hashCode from the same components.

JPA entities and other mutable objects are never keys in long-lived maps or caches, because their ids change on persist and they may be proxies; we key by a value like a CustomerId record. Equals and hashCode are generated, never hand-written partially, and every key class has an EqualsVerifier test that checks the contract.

Each key type normalises its inputs in its constructor, for example lowercasing with Locale.ROOT and fixing BigDecimal scale, so equal meanings become equal keys.

For enforcement, I would put Error Prone in the shared build to catch equals overloads and mismatches, add ArchUnit rules such as no entity types as cache keys, keep a short review checklist, and make the shared library's own APIs follow the rules, with each rule linked to the incident behind it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your platform team maintains shared libraries used by many services, and several...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/68614ebed3/