Skip to content

Lesson 4 of 14 · 18m

The equals/hashCode Contract — and Why String Is Immutable

How a mutated key vanishes from a HashSet, what records give you for free, and why passwords live in char[] instead of String.

A HashSet<User> reports contains(user) == false for an object you can see sitting inside it in the debugger. No exception, no warning — the collection simply cannot find its own contents anymore. Someone mutated a field that hashCode() reads after insertion, and the object is now filed in a bucket it will never be looked up from. That's the equals/hashCode contract breaking in production.

The contract you're actually signing

HashMap and HashSet place an object by its hashCode() at insert time, then compare candidates with equals() inside that bucket. The contract (it lives in java.lang.Object's javadoc): equals must be reflexive, symmetric, transitive, consistent, and false against null; equal objects must produce equal hash codes. Override equals alone and equal objects scatter across different buckets — lookups fail intermittently, only on some inserts, only on some hashes.

// Both fields participate in both methods, or neither.
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof User u)) return false;
    return id.equals(u.id);
}
public int hashCode() { return id.hashCode(); }

Two rules keep you out of the pit: use immutable fields in both methods (a mutable key field is the bug from the first paragraph), and never build them yourself when a record does it for free — Java 16+ records generate correct equals, hashCode, and toString from the components. For ordinary classes, Objects.equals(a, b) handles nulls without the ternary ceremony.

The JPA trap deserves its own callout: entities whose equals uses a database-assigned ID are all "equal" when id is null pre-persist, then silently unequal after save. Use a stable business key — a natural key like orderNumber, not the surrogate id — or accept Object identity until you understand why Hibernate's own docs warn against it. And Objects.hash(a, b, c) boxes every argument into an Object[] — correct, but allocation-hot; on a hot path write the 31 * x + y by hand or use a record.

Why String is immutable — and why you should care

String immutability isn't a performance quirk; it's a load-bearing assumption across the whole platform. Strings are hash keys (their hashCode is cached once computed — safe only because the value can't change), class names the ClassLoader resolves, file paths in Path.of, URLs, and map keys in every config file ever written. If String were mutable, a thread could mutate the path between your permission check and your file open — a textbook TOCTOU you never even see. The string constant pool (String.intern()) and safe sharing between threads fall out of immutability for free.

The flip side is a real security behavior: a password held in a String stays in the heap until GC, visible in every heap dump and crash artifact. That's why JPasswordField.getPassword() returns char[] — you can Arrays.fill it to zero when done. Your credential classes should do the same.

Try this

Build a User with a mutable name in hashCode, insert it into a HashSet, mutate name, and call contains. Watch it fail. Then convert User to a record and try to break it — you can't, and that is the point of paying attention to the contract.

Pitfalls

  • == on strings compares references; the constant pool makes "a" == "a" true in tests while the same comparison fails on strings built at runtime. Always .equals.
  • Lombok's @EqualsAndHashCode on a JPA entity pulls in every field — including lazy collections that fire queries. Exclude fields deliberately.
  • compareTo is a third contract: it must agree with equals or TreeSet/TreeMap will drop "duplicates" that equals considers distinct — the collection that silently loses your object is the same bug, a different doorway.
  • String immutability is also why == on interned literals "works" until a runtime-built string breaks it — new String("a") == "a" is false; .equals is the only comparison that means what you mean.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.