equals and hashCode in Java
Every Java object inherits equals and hashCode from Object, and by default both are based on identity: two objects are equal only if they are the same object. Classes that represent values, such as points, money or IDs, must override both, and they must agree with each other or HashMap and HashSet silently stop working. This page explains the contract and how hash tables use it, then shows the classic bugs with running code and the correct ways to fix them.
Contents
Identity, equality and the contract
Java has two ideas of "the same":
- Identity, tested with
: two references point to the very same object.== - Equality, tested with
: two objects represent the same value, such as twoequals objects containing "abc".String
Object.equals==Object.hashCodeObject
| Rule | Meaning |
|---|---|
| Reflexive | x.equals(x) |
| Symmetric | x.equals(y)y.equals(x) |
| Transitive | If xyyzxz |
| Consistent | Repeated calls give the same answer while the objects do not change |
| Non-null | x.equals(null) |
| Equal objects, equal hash codes | If x.equals(y)x.hashCode() == y.hashCode() |
| Not the reverse | Unequal objects may share a hash code (a collision), but fewer collisions mean faster hash tables |
The hash code rule exists because of how HashMapHashSethashCode()equalsequals
What goes wrong without them
The program uses a point with xyequals
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class BrokenKeys {
// No equals or hashCode: identity comparison inherited from Object
static class PointNone {
final int x;
final int y;
PointNone(int x, int y) {
this.x = x;
this.y = y;
}
}
// equals overridden, hashCode forgotten. javac -Xlint:overrides warns about exactly
// this; the annotation silences it because the bug is the point of the demo.
@SuppressWarnings("overrides")
static class PointEqualsOnly {
final int x;
final int y;
PointEqualsOnly(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
return o instanceof PointEqualsOnly p && p.x == x && p.y == y;
}
}
public static void main(String[] args) {
Set<PointNone> a = new HashSet<>();
a.add(new PointNone(1, 2));
a.add(new PointNone(1, 2));
System.out.println("no equals/hashCode: set size " + a.size()
+ ", contains(1,2) " + a.contains(new PointNone(1, 2)));
PointEqualsOnly p1 = new PointEqualsOnly(1, 2);
PointEqualsOnly p2 = new PointEqualsOnly(1, 2);
System.out.println("equals only: p1.equals(p2) = " + p1.equals(p2)
+ ", same hashCode = " + (p1.hashCode() == p2.hashCode()));
Map<PointEqualsOnly, String> labels = new HashMap<>();
labels.put(p1, "start");
System.out.println("equals only: map.get(equal key) = " + labels.get(p2));
}
}
Output:
no equals/hashCode: set size 2, contains(1,2) false
equals only: p1.equals(p2) = true, same hashCode = false
equals only: map.get(equal key) = null
- With neither method, two points (1, 2) are different objects, so the set kept both and a third (1, 2) was not found.
- With only
,equals is true but their hash codes differ, sop1.equals(p2) looked in another bucket and returnedmap.get(p2) , although an equal key is in the map. This bug is intermittent in practice: occasionally two hash codes happen to land in the same bucket and the lookup works.null - javac warns about the second case with
("overrides equals, but neither it nor any superclass overrides hashCode"); the program suppresses the warning only because the bug is the point of the demo.-Xlint:overrides
A correct implementation, and records
The program writes equalshashCode
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class CorrectPoint {
static final class Point {
private final int x;
private final int y;
private final String label; // not part of identity: excluded on purpose
Point(int x, int y, String label) {
this.x = x;
this.y = y;
this.label = label;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true; // same object
}
if (!(o instanceof Point other)) {
return false; // also handles null
}
return x == other.x && y == other.y; // the fields that define identity
}
@Override
public int hashCode() {
return Objects.hash(x, y); // the SAME fields as equals
}
@Override
public String toString() {
return label + "(" + x + "," + y + ")";
}
}
// A record generates equals, hashCode and toString from all its components
record Coord(int x, int y) {
}
public static void main(String[] args) {
Set<Point> set = new HashSet<>();
set.add(new Point(1, 2, "a"));
set.add(new Point(1, 2, "b")); // equal to the first: not added
set.add(new Point(3, 4, "c"));
System.out.println("set: " + set.size() + " points, contains (1,2): "
+ set.contains(new Point(1, 2, "z")));
System.out.println("equals(null): " + new Point(0, 0, "o").equals(null));
System.out.println("record equals: " + new Coord(1, 2).equals(new Coord(1, 2))
+ ", hash equal: " + (new Coord(1, 2).hashCode() == new Coord(1, 2).hashCode()));
// Equal hash codes do not imply equality: collisions are allowed
System.out.println("\"Aa\" and \"BB\" hash: " + "Aa".hashCode() + " " + "BB".hashCode()
+ ", equal: " + "Aa".equals("BB"));
}
}
Output:
set: 2 points, contains (1,2): true
equals(null): false
record equals: true, hash equal: true
"Aa" and "BB" hash: 2112 2112, equal: false
- The standard shape of
: returnequals for the same object, returntrue if the argument is not the right type (pattern matchingfalse also handlesinstanceof ), then compare the fields that define identity.null uses exactly the same fields, throughhashCode . The label is in neither, so points "a" and "b" at (1, 2) are equal and the set kept only one of them. Using a field inObjects.hash but not inhashCode breaks the contract; the reverse just causes more collisions.equals- A
generatesrecord ,equals andhashCode from all its components, correctly, which is the easiest fix for value classes; thetoStringrecords page covers them. - "Aa" and "BB" both hash to 2112 but are not equal. Collisions are normal; they only cost speed.
Inheritance breaks symmetry
Adding a field in a subclass is where equalsinstanceofgetClass()
import java.util.Objects;
public class InheritanceTrap {
static class Point {
final int x;
final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
return o instanceof Point p && p.x == x && p.y == y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
static class ColorPoint extends Point {
final String color;
ColorPoint(int x, int y, String color) {
super(x, y);
this.color = color;
}
@Override
public boolean equals(Object o) {
return o instanceof ColorPoint cp && super.equals(cp) && cp.color.equals(color);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), color);
}
}
// The getClass() version: objects of different classes are never equal
static class StrictPoint {
final int x;
final int y;
StrictPoint(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (o == null || o.getClass() != getClass()) {
return false;
}
StrictPoint p = (StrictPoint) o;
return p.x == x && p.y == y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
static class StrictColorPoint extends StrictPoint {
final String color;
StrictColorPoint(int x, int y, String color) {
super(x, y);
this.color = color;
}
@Override
public boolean equals(Object o) {
return super.equals(o) && ((StrictColorPoint) o).color.equals(color);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), color);
}
}
public static void main(String[] args) {
Point p = new Point(1, 2);
ColorPoint red = new ColorPoint(1, 2, "red");
System.out.println("p.equals(red): " + p.equals(red));
System.out.println("red.equals(p): " + red.equals(p) + " <- not symmetric");
// Transitivity breaks too if ColorPoint tries to be lenient with plain Points
StrictPoint sp = new StrictPoint(1, 2);
StrictColorPoint sRed = new StrictColorPoint(1, 2, "red");
System.out.println("getClass version: sp.equals(sRed) = " + sp.equals(sRed)
+ ", sRed.equals(sp) = " + sRed.equals(sp));
}
}
Output:
p.equals(red): true
red.equals(p): false <- not symmetric
getClass version: sp.equals(sRed) = false, sRed.equals(sp) = false
- With
, a plaininstanceof considers the redPoint equal (it is aColorPoint with the same coordinates), but thePoint does not consider the plain point equal (it is not aColorPoint ). That breaks symmetry, and aColorPoint can then behave differently depending on which object was added first.HashSet - With
, objects of different classes are never equal, in both directions, so the contract holds. The cost is that a harmless subclass, for example one that only adds logging, is never equal to its parent.getClass() != o.getClass() - Neither approach lets a subclass add a field to equality and keep all the rules; Joshua Bloch explains why in Effective Java (item 10). The usual solutions are to make value classes
(records are), or to use composition: afinal that has aColorPoint rather than being one.Point
Mutable keys, arrays, doubles and identity hashes
These four cases follow the rules on paper and still surprise people. Each is shown with the smallest example that triggers it.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class MutableKeys {
static final class Tag {
String name; // mutable, and used in hashCode
Tag(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
return o instanceof Tag t && t.name.equals(name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
record Polygon(int[] xs) { } // array component: identity equals
record Measurement(double value) { }
public static void main(String[] args) {
// 1. Changing a key after adding it to a HashSet loses it
Set<Tag> tags = new HashSet<>();
Tag tag = new Tag("java");
tags.add(tag);
tag.name = "kotlin"; // its hash changes, its bucket does not
System.out.println("contains(same object): " + tags.contains(tag));
System.out.println("contains(new \"java\"): " + tags.contains(new Tag("java")));
System.out.println("size: " + tags.size() + ", but iterating finds: "
+ tags.iterator().next().name);
// 2. Records compare arrays by reference, not by contents
Polygon a = new Polygon(new int[] {0, 1, 1});
Polygon b = new Polygon(new int[] {0, 1, 1});
System.out.println("records with equal arrays: equals = " + a.equals(b)
+ ", Arrays.equals = " + Arrays.equals(a.xs(), b.xs()));
// 3. Doubles: records and Double.equals use bits, so NaN equals NaN and 0.0 != -0.0
System.out.println("NaN == NaN: " + (Double.NaN == Double.NaN)
+ ", record(NaN).equals(record(NaN)): "
+ new Measurement(Double.NaN).equals(new Measurement(Double.NaN)));
System.out.println("0.0 == -0.0: " + (0.0 == -0.0) + ", record(0.0).equals(record(-0.0)): "
+ new Measurement(0.0).equals(new Measurement(-0.0)));
// 4. Default hashCode is an identity hash, not a memory address
Object o = new Object();
System.out.println("Object.hashCode == identityHashCode: "
+ (o.hashCode() == System.identityHashCode(o)));
System.out.println("Objects.equals(null, null): " + Objects.equals(null, null));
}
}
Output:
contains(same object): false
contains(new "java"): false
size: 1, but iterating finds: kotlin
records with equal arrays: equals = false, Arrays.equals = true
NaN == NaN: false, record(NaN).equals(record(NaN)): true
0.0 == -0.0: true, record(0.0).equals(record(-0.0)): false
Object.hashCode == identityHashCode: true
Objects.equals(null, null): true
- A
was added to a set as "java", then renamed to "kotlin". The set stored it in the bucket for "java", so a lookup with the same object now searches the "kotlin" bucket and fails, and a lookup for "java" finds an object that is no longer equal. The entry is stuck: still counted and iterated, but unreachable by lookup. Never change fields used inTag while the object is in a hash-based collection; ideally keys are immutable.hashCode - A record's generated
compares components withequals , and arrays inherit identityequals fromequals . Two polygons with equal arrays were therefore not equal. Use aObject component, or overrideList andequals withhashCode andArrays.equals .Arrays.hashCode - For
components, records compare likedouble :Double.compare equalsNaN (unlikeNaN ), and 0.0 does not equal -0.0 (unlike== ). This keeps the contract reflexive, which== on== would not.NaN - The default
is the same ashashCode . It is not a memory address: HotSpot generates it once, stores it in the object header, and keeps it even when the garbage collector moves the object.System.identityHashCode
Hash quality and speed
A hashCodehashCode
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class HashQuality {
record GoodKey(int id) { }
static final class ConstantHashKey {
final int id;
ConstantHashKey(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
return o instanceof ConstantHashKey k && k.id == id;
}
@Override
public int hashCode() {
return 42; // legal, but every key collides
}
}
static final class SumHashKey { // a common weak formula
final int x;
final int y;
SumHashKey(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
return o instanceof SumHashKey k && k.x == x && k.y == y;
}
@Override
public int hashCode() {
return x + y;
}
}
public static void main(String[] args) {
int n = 20000;
long t0 = System.nanoTime();
Map<GoodKey, Integer> good = new HashMap<>();
for (int i = 0; i < n; i++) {
good.put(new GoodKey(i), i);
}
long t1 = System.nanoTime();
Map<ConstantHashKey, Integer> bad = new HashMap<>();
for (int i = 0; i < n; i++) {
bad.put(new ConstantHashKey(i), i);
}
long t2 = System.nanoTime();
System.out.printf("20,000 puts with a good hashCode: %,6d ms%n", (t1 - t0) / 1000000);
System.out.printf("20,000 puts with hashCode() == 42: %,6d ms%n", (t2 - t1) / 1000000);
// How many distinct hash values do 100 x 100 grid points get?
Set<Integer> sums = new HashSet<>();
Set<Integer> hashes = new HashSet<>();
for (int x = 0; x < 100; x++) {
for (int y = 0; y < 100; y++) {
sums.add(new SumHashKey(x, y).hashCode());
hashes.add(Objects.hash(x, y));
}
}
System.out.println("10,000 points: x + y gives " + sums.size()
+ " distinct hashes, Objects.hash gives " + hashes.size());
}
}
Output (2-CPU Linux machine, JDK 21):
20,000 puts with a good hashCode: 35 ms
20,000 puts with hashCode() == 42: 864 ms
10,000 points: x + y gives 199 distinct hashes, Objects.hash gives 3169
- With every key in the same bucket, each
had to search the colliding entries, and filling the map was many times slower. Since Java 8,put turns a crowded bucket into a balanced tree, but the tree can only speed up lookups when the keys areHashMap ; these are not, so each lookup still compares against many entries.Comparable - Adding the fields,
, is a common weak formula: (1, 2) and (2, 1) collide, and the 10,000 points produced only 199 distinct values.x + y , which computesObjects.hash , gave 3,169, much better though still not one per point, because small coordinates make small hashes.31 × (31 + x) + y spreads the high bits of every hash code to compensate.HashMap creates an array and boxes the fields on every call. In performance-critical code, writeObjects.hash , or cache the hash code of an immutable object, as31 * Integer.hashCode(x) + Integer.hashCode(y) does.String
Checklist
| Do | Avoid |
|---|---|
| Use a record for value classes | Hand-writing methods a record would generate |
| Override both methods, using the same fields | Overriding only equals |
Use Objects.equalsnull | field.equals(other.field) |
Use Double.compareArrays.equals | ==equals |
Make value classes final | Subclasses that add fields to equality |
| Keep keys immutable | Changing a key while it is in a HashMapHashSet |
Make compareToequals | Treating equal-by-compareToequals |
For how these methods fit with toStringObject