Why must you override both equals() and hashCode() in Java?
The contract: equal objects must have the same hash code. If you override equals() but not hashCode(), two equal objects get different hash codes, and a HashSet keeps both:
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Main {
static class Bad {
final String name;
Bad(String name) { this.name = name; }
@Override public boolean equals(Object o) { return o instanceof Bad b && b.name.equals(name); }
}
static class Good {
final String name;
Good(String name) { this.name = name; }
@Override public boolean equals(Object o) { return o instanceof Good g && g.name.equals(name); }
@Override public int hashCode() { return Objects.hash(name); }
}
public static void main(String[] args) {
Set<Bad> bad = new HashSet<>();
bad.add(new Bad("Riya"));
bad.add(new Bad("Riya"));
System.out.println("Without hashCode: " + bad.size()); // wrong: 2
Set<Good> good = new HashSet<>();
good.add(new Good("Riya"));
good.add(new Good("Riya"));
System.out.println("With hashCode: " + good.size()); // right: 1
}
}
Output
Without hashCode: 2
With hashCode: 1
The easy way: use a record, which writes both methods for you (Java Records).
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |