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
@EqualsAndHashCodeon a JPA entity pulls in every field — including lazy collections that fire queries. Exclude fields deliberately. compareTois a third contract: it must agree withequalsorTreeSet/TreeMapwill drop "duplicates" thatequalsconsiders distinct — the collection that silently loses your object is the same bug, a different doorway.Stringimmutability is also why==on interned literals "works" until a runtime-built string breaks it —new String("a") == "a"is false;.equalsis the only comparison that means what you mean.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Java Pulled Primitive Patterns After Five Previews. JDK 28 Won't Compile Them.
Primitive types in patterns, instanceof, and switch previewed in every JDK from 23 to 27. On November 9 the Amber team withdrew the feature, and it won't be in JDK 28 even with --enable-preview. Here's why Valhalla changed the plan, what replaces it, and how to rewrite code that used it.
Your Minecraft Server Wants Java 25, Not Java 26
Every six months the same thread appears and nobody maps the JVM engineering onto what a Minecraft server actually does. This does — version by version, with the flag most guides still tell you to set that will eventually stop your server from booting.
Java 20: What's Coming Next
With Java 19 having just arrived on September 20, Java 20 is next on the docket, expected in March 2023. The release potentially could add new functionality for universal generics, immutable data, and string templates and finalize capabilities such as record patterns. The current OpenJDK…
What's next for Java? JDK 20 is coming soon
With Java 19 having just arrived on September 20, Java 20 is next on the docket, expected in March 2023. The release potentially could add new functionality for universal generics, immutable data, and string templates and finalize capabilities such as record patterns. Why is it named Java?When…