Java Design Program · CD02
Override equals() and hashCode() Correctly in Java
A HashSet first uses hashCode() to pick a bucket, then equals() to compare. If equal objects can have different hash codes, the set will not find them.
Problem Statement
Write a Point class so that two points with the same x and y are equal, and a HashSet containing one of them reports that it contains the other.
The implementation must follow the contract: equal objects have equal hash codes, equals() is reflexive, symmetric and transitive, and equals(null) is false.
Input/Output Examples
set.add(new Point(1, 2)); set.contains(new Point(1, 2))OutputtrueExplanation: the two objects are different instances but equal by value.add an equal point twiceOutputsize 1Explanation: the set recognises the second point as a duplicate.point.equals(null)OutputfalseExplanation: equals() must handle null without throwing.Visual Explanation
- hashCode()buckethash(1, 2)pick the bucket
- equals()compare(1, 2)(1, 2)x == x and y == y match
- Without hashCode()buckets#a#bidentity hashes differ wrong bucket
- Donecontains: true
hashCode() chooses the bucket, then equals() confirms the match. If only equals() is overridden, the two points usually land in different buckets and are never compared.That is why the two methods must always be overridden together, and why hashCode() must use the same fields as equals().
Approaches
Both approaches give identical behaviour. The first writes the methods by hand; the second lets a record generate them.
Approach 1: Manual equals() and Objects.hash() (Recommended)
Idea: compare the same fields in equals() that you pass to Objects.hash() in hashCode().
- Return
truefor the same reference. - Return
falseif the other object is not aPoint(this also coversnull). - Compare
xandy. - Return
Objects.hash(x, y)fromhashCode().
Time: O(1) · Space: O(1).
Approach 2: Record
Idea: declare record Point(int x, int y); the compiler generates value-based equals(), hashCode() and toString().
- Declare the record with its components.
- Use it in hash-based collections as usual.
- Override the methods only if some components should be ignored.
Time: O(1) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Manual equals() and Objects.hash() (Recommended)
Making the class final keeps equals() symmetric, because no subclass can add fields that break it.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class EqualsHashCodeManual {
static final class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Point)) {
return false;
}
Point other = (Point) o;
return x == other.x && y == other.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y); // equal points must give equal hash codes
}
}
public static void main(String[] args) {
Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
Point probe = new Point(1, 2);
System.out.println("contains(new Point(1, 2)): " + set.contains(probe));
System.out.println("equals: " + new Point(1, 2).equals(probe));
System.out.println("same hashCode: " + (new Point(1, 2).hashCode() == probe.hashCode()));
set.add(new Point(1, 2));
System.out.println("size after adding an equal point: " + set.size());
System.out.println("equals(null): " + probe.equals(null));
}
}
contains(new Point(1, 2)): true equals: true same hashCode: true size after adding an equal point: 1 equals(null): false
Time complexity: O(1) · Space complexity: O(1).
Approach 2: Record
The generated methods always use all components consistently, which removes a whole class of bugs.
import java.util.HashSet;
import java.util.Set;
public class EqualsHashCodeRecord {
// A record generates equals(), hashCode() and toString() from its components
record Point(int x, int y) { }
public static void main(String[] args) {
Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
Point probe = new Point(1, 2);
System.out.println("contains(new Point(1, 2)): " + set.contains(probe));
System.out.println("equals: " + new Point(1, 2).equals(probe));
System.out.println("same hashCode: " + (new Point(1, 2).hashCode() == probe.hashCode()));
set.add(new Point(1, 2));
System.out.println("size after adding an equal point: " + set.size());
System.out.println("equals(null): " + probe.equals(null));
}
}
contains(new Point(1, 2)): true equals: true same hashCode: true size after adding an equal point: 1 equals(null): false
Time complexity: O(1) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Manual equals() and Objects.hash() | O(1) | O(1) |
| Record | O(1) | O(1) |
Both methods do a constant amount of work for a fixed number of fields. With a good hash function, HashSet lookups take O(1) time on average.
Interview Tips and Recommended Approach
- Override both or neither. Overriding only
equals()breaks every hash-based collection. - Use the same fields in both methods. A field used in
equals()but not inhashCode()is fine; the reverse is a bug. - Avoid mutable fields in the hash. Changing a field after inserting the object makes it unreachable in the set.
- Write the signature
equals(Object o).equals(Point p)is an overload, not an override, and is never called by collections.
Recommended Approach: Manual equals() and Objects.hash()
Why: it shows exactly what the contract requires. In new code, a record gives you the same correct methods for free.