I Stopped Overriding equals() Without hashCode(). Here’s the Bug That Taught Me Why.
I once added the same logical object to a HashSet twice, watched the set report a size of two instead of one, and spent longer than I want to admit assuming the bug was somewhere else. The object had a perfectly reasonable equals() method. Two instances with the same fields returned true when compared directly. The set just didn’t seem to care.
The class overrode equals(). It didn’t override hashCode(). That single omission was the entire bug.
What a HashSet actually does when you call add()
A HashSet doesn’t scan every element and compare it against the new one with equals(). That would work, but it would be linear, and the entire reason anyone reaches for a hash-based collection is to avoid exactly that. Instead, add() first calls hashCode() on the object, uses that number to pick a bucket, and only compares against the other objects already sitting in that same bucket, using equals(). If two objects you consider equal produce different hash codes, they can end up in different buckets entirely, and equals() never even gets called between them. As far as the set is concerned, they’re two unrelated objects that happen to live in different neighborhoods.
This is exactly what happens when you override equals() and leave hashCode() at its default. The default hashCode(), inherited from Object, is based on the object’s identity, essentially its memory address. Two separate instances get two different default hash codes even when every field inside them is identical. Your careful equals() override never gets a chance to run, because the two objects were routed to different buckets before any comparison happened.
<button data-code="public class Point {
private final int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof Point p)) return false;
return x == p.x && y == p.y;
}
// hashCode() not overridden — still Object's identity-based version
}
var points = new HashSet();
points.add(new Point(3, 4));
points.add(new Point(3, 4));
System.out.println(points.size()); // 2, not 1
System.out.println(points.contains(new Point(3, 4))); // false, because the lookup searches a different bucket” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
public class Point {
private final int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof Point p)) return false;
return x == p.x && y == p.y;
}
// hashCode() not overridden — still Object's identity-based version
}
var points = new HashSet<Point>();
points.add(new Point(3, 4));
points.add(new Point(3, 4));
System.out.println(points.size()); // 2, not 1
System.out.println(points.contains(new Point(3, 4))); // false, because the lookup searches a different bucket
public class Point {
private final int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof Point p)) return false;
return x == p.x && y == p.y;
}
// hashCode() not overridden — still Object's identity-based version
}
var points = new HashSet<Point>();
points.add(new Point(3, 4));
points.add(new Point(3, 4));
System.out.println(points.size()); // 2, not 1
System.out.println(points.contains(new Point(3, 4))); // false, because the lookup searches a different bucket
Both Point(3, 4) instances are equals() to each other by every reasonable definition. The set holds two of them anyway, and a contains() check for a logically identical point comes back false, because the point you’re checking against hashes to a different bucket than the ones already stored. Nothing throws an exception. Nothing logs a warning. The set just quietly fails to do the one thing you added it for.
The contract, stated precisely
The rule is documented directly on Object.hashCode(), and it’s worth stating in the exact direction it actually runs, because people frequently get it backwards: if two objects are equal according to equals(), they must return the same hash code. The reverse is not required. Two unequal objects are allowed to share a hash code — that’s called a collision, and every hash-based collection is built to handle collisions correctly through the bucket-and-compare mechanism described above. What’s never allowed is two equal objects disagreeing on their hash code, because that’s the one situation the bucket mechanism has no way to recover from.
equals() itself carries its own contract, and an interviewer asking about this is usually listening for whether you know these by name, not just that “equal things should be equal”:
Reflexive: x.equals(x) must always be true. Symmetric: if x.equals(y) is true, y.equals(x) must also be true. Transitive: if x.equals(y) and y.equals(z), then x.equals(z) must hold. Consistent: repeated calls to x.equals(y) return the same result as long as neither object has changed. And x.equals(null) must return false, never throw.
Symmetry is the one that breaks most often in practice, usually through inheritance. If a subclass overrides equals() to compare its own extra field, and the superclass version doesn’t know about that field, you can end up with parent.equals(child) returning true while child.equals(parent) returns false, because the child’s more specific check fails a comparison the parent’s looser check would have passed. This is the real argument behind the long-running instanceof versus getClass() debate in equals implementations. Using getClass() == other.getClass() instead of instanceof refuses to consider a subclass instance equal to a superclass instance at all, which sidesteps the symmetry break entirely at the cost of being stricter about what “equal” means across a class hierarchy. There’s no universally correct answer here, only a trade-off you should be able to explain: instanceof is more permissive and risks symmetry violations under inheritance, getClass() is safer but means a subclass can never be equal to its parent even when that would be semantically reasonable.
The mutable field trap
There’s a second failure mode that has nothing to do with forgetting hashCode() and everything to do with which fields you use inside it. If an object’s hash code is computed from a field that later changes, and that object is already sitting inside a HashSet or used as a HashMap key, the collection effectively loses track of it. The object is still physically in the same bucket it was placed into originally, but a contains() or get() call now computes a different bucket based on the field’s new value and looks in the wrong place entirely.
<button data-code="var set = new HashSet<List>();
var mutableKey = new ArrayList(List.of(1, 2, 3));
set.add(mutableKey);
mutableKey.add(4); // the list's hashCode changes because ArrayList's hashCode is content-based
System.out.println(set.contains(mutableKey)); // false, even though the object reference is identical” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
var set = new HashSet<List<Integer>>();
var mutableKey = new ArrayList<>(List.of(1, 2, 3));
set.add(mutableKey);
mutableKey.add(4); // the list's hashCode changes because ArrayList's hashCode is content-based
System.out.println(set.contains(mutableKey)); // false, even though the object reference is identical
var set = new HashSet<List<Integer>>();
var mutableKey = new ArrayList<>(List.of(1, 2, 3));
set.add(mutableKey);
mutableKey.add(4); // the list's hashCode changes because ArrayList's hashCode is content-based
System.out.println(set.contains(mutableKey)); // false, even though the object reference is identical
The object you’re asking about is the exact same reference sitting in the set. contains() still returns false, because it recomputes the hash code from the list’s current contents, gets a different bucket than the one the object actually lives in, and never finds it. The object hasn’t moved. The collection simply has no reason to look in the bucket where it was originally stored. The practical lesson: never use mutable fields in hashCode() for an object that might end up as a map key or set element, and if a class is naturally mutable, consider whether it should implement equals()/hashCode() at all, or whether identity-based comparison is actually the safer default for that type.
How to actually write these correctly
java.util.Objects has carried the boilerplate for this since Java 7, and there’s rarely a reason to hand-roll it anymore:
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof Point p)) return false;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof Point p)) return false;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
Objects.hash(x, y) combines the hash codes of every argument using the same field-combination approach you’d write by hand, and it guarantees the property that actually matters here: two Point instances with the same x and y produce the same result, every time. The fields used in hashCode() should be exactly the same fields that participate in equals(). If hashCode() includes additional state that equals() ignores, or omits state that equals() compares, you risk violating the contract that equal objects must produce equal hash codes. Two objects equals() considers identical but whose extra field differs will compute different hash codes if that field feeds into hashCode(), which is precisely the violation the contract exists to prevent.
Records make the whole problem disappear
If you’re on Java 16 or later and the class is a plain data holder, a record generates a correct equals(), hashCode(), and toString() for you automatically, based on every field in the record’s declaration, and it’s the one implementation Java can guarantee is consistent because the compiler writes it rather than you:
public record Point(int x, int y) {}
public record Point(int x, int y) {}
That single line produces exactly the equals() and hashCode() shown above, with the contract satisfied by construction. Records are designed for value semantics, so the generated implementations compare every record component automatically. It doesn’t help you when a class needs actual behavior beyond holding fields, and it doesn’t retroactively fix classes you can’t turn into records, but for the plain value-holding case, this is the strongest possible fix: you cannot make this specific mistake if the compiler is the one writing the code.
What to actually remember for an interview
If an interviewer asks about equals() and hashCode(), the answer they’re usually looking for is this: equal objects must produce equal hash codes; hash-based collections use hashCode() to find the bucket and equals() only to compare objects inside that bucket; overriding one without the other breaks that lookup algorithm.
If you’re curious how these same identity and equality questions play out on the Rust side, that’s the whole premise of the book I’ve been writing: every classic data structure built once in Rust and once in Java, side by side, so you can see exactly where each language’s rules force a different decision. Ownership vs. Reference: Data Structures and Algorithms in Rust and Java
For the Rust foundations that series builds on: Zero to Rust: A Systems Programmer’s Field Guide — $7 · Free 20-page sample


