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 equals: two objects represent the same value, such as two String objects containing "abc".

Object.equals just uses ==, and Object.hashCode returns a number tied to the object's identity. That is right for objects with identity, like a database connection. For value objects you override both, and the Javadoc of Object defines rules the overrides must follow:

The equals and hashCode contract
RuleMeaning
Reflexivex.equals(x) is true
Symmetricx.equals(y) equals y.equals(x)
TransitiveIf x equals y and y equals z, then x equals z
ConsistentRepeated calls give the same answer while the objects do not change
Non-nullx.equals(null) is false, never an exception
Equal objects, equal hash codesIf x.equals(y), then x.hashCode() == y.hashCode()
Not the reverseUnequal objects may share a hash code (a collision), but fewer collisions mean faster hash tables

The hash code rule exists because of how HashMap and HashSet work. They first use hashCode() to pick a bucket, and only then call equals on the few entries in that bucket. If two equal objects have different hash codes, the table looks in the wrong bucket and never calls equals at all. See HashMap internals for the details.

What goes wrong without them

The program uses a point with x and y coordinates as a key, twice: once with neither method overridden, and once with only equals, the most common mistake.

Java
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:

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, p1.equals(p2) is true but their hash codes differ, so map.get(p2) looked in another bucket and returned null, 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.
  • javac warns about the second case with -Xlint:overrides ("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.

A correct implementation, and records

The program writes equals and hashCode by hand for a point with a label that is deliberately not part of its identity, then compares the same thing done by a record, and shows that equal hash codes do not imply equal objects.

Java
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:

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 equals: return true for the same object, return false if the argument is not the right type (pattern matching instanceof also handles null), then compare the fields that define identity.
  • hashCode uses exactly the same fields, through Objects.hash. 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 in hashCode but not in equals breaks the contract; the reverse just causes more collisions.
  • A record generates equals, hashCode and toString from all its components, correctly, which is the easiest fix for value classes; the records 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 equals becomes genuinely hard. The program extends a point with a color, first with instanceof checks and then with getClass() checks.

Java
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:

Output
p.equals(red): true
red.equals(p): false  <- not symmetric
getClass version: sp.equals(sRed) = false, sRed.equals(sp) = false
  • With instanceof, a plain Point considers the red ColorPoint equal (it is a Point with the same coordinates), but the ColorPoint does not consider the plain point equal (it is not a ColorPoint). That breaks symmetry, and a HashSet can then behave differently depending on which object was added first.
  • With getClass() != o.getClass(), 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.
  • 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 final (records are), or to use composition: a ColorPoint that has a Point rather than being one.

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.

Java
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:

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
  1. A Tag 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 in hashCode while the object is in a hash-based collection; ideally keys are immutable.
  2. A record's generated equals compares components with equals, and arrays inherit identity equals from Object. Two polygons with equal arrays were therefore not equal. Use a List component, or override equals and hashCode with Arrays.equals and Arrays.hashCode.
  3. For double components, records compare like Double.compare: NaN equals NaN (unlike ==), and 0.0 does not equal -0.0 (unlike ==). This keeps the contract reflexive, which == on NaN would not.
  4. The default hashCode is the same as System.identityHashCode. 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.

Hash quality and speed

A hashCode that returns the same number for everything is legal but turns a hash table into a slow search. The program fills one map with well-hashed keys and one with keys whose hashCode is always 42, then counts how many distinct hash codes two formulas give for a 100 by 100 grid of points. It is a rough, single-run comparison.

Java
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):

Output
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 put had to search the colliding entries, and filling the map was many times slower. Since Java 8, HashMap turns a crowded bucket into a balanced tree, but the tree can only speed up lookups when the keys are Comparable; these are not, so each lookup still compares against many entries.
  • Adding the fields, x + y, is a common weak formula: (1, 2) and (2, 1) collide, and the 10,000 points produced only 199 distinct values. Objects.hash, which computes 31 × (31 + x) + y, gave 3,169, much better though still not one per point, because small coordinates make small hashes. HashMap spreads the high bits of every hash code to compensate.
  • Objects.hash creates an array and boxes the fields on every call. In performance-critical code, write 31 * Integer.hashCode(x) + Integer.hashCode(y), or cache the hash code of an immutable object, as String does.

Checklist

Writing equals and hashCode
DoAvoid
Use a record for value classesHand-writing methods a record would generate
Override both methods, using the same fieldsOverriding only equals
Use Objects.equals for fields that may be nullfield.equals(other.field) without a null check
Use Double.compare and Arrays.equals for doubles and arrays== on doubles; equals on arrays
Make value classes final, or use compositionSubclasses that add fields to equality
Keep keys immutableChanging a key while it is in a HashMap or HashSet
Make compareTo consistent with equals for sorted collectionsTreating equal-by-compareTo and equal-by-equals as the same thing (see BigDecimal)

For how these methods fit with toString and the rest of Object, see the Object class.