equals and hashCode

Object.equals compares references, so two objects with the same fields are unequal until a class overrides it. The override has to come with hashCode, because a hash collection finds an object by its hash before it asks whether it is equal. This lesson shows the failure that a missing hashCode produces.

The contract

The equals method must be reflexive, symmetric, transitive and consistent, and it must return false for null. The hashCode method must return the same number for two objects that are equal, and it may return anything for two objects that are not. The second rule is the one that is forgotten.

Object.hashCode is derived from the identity of the object, so two equal points have two different hashes unless the class says otherwise. A HashSet uses the hash to choose a bucket, so it looks for the equal object in the wrong place and reports that it is not there.

equals without hashCode

The class below overrides equals and nothing else. The compiler warns about it with -Xlint:overrides, and the program then fails to find the point it just put into the set.

The file NoHash.java:

import java.util.HashSet; import java.util.Set; public class NoHash { public static void main(String[] args) { Set<Point> points = new HashSet<>(); points.add(new Point(1, 2)); System.out.println("contains: " + points.contains(new Point(1, 2))); System.out.println("size: " + points.size()); } } 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 other) { if (!(other instanceof Point)) { return false; } Point point = (Point) other; return x == point.x && y == point.y; } }

javac -Xlint:all NoHash.java
java NoHash

NoHash.java:13: warning: [overrides] Class Point overrides equals, but neither it nor any superclass overrides hashCode method
class Point {
^
1 warning
contains: false
size: 1

The set holds one point and cannot find it. size is 1 because an add always inserts; contains is false because the search starts from a different hash. The warning names the class and the exact problem, which is why every build of this course uses -Xlint:all.

equals with hashCode

The fix is one more override, and Objects.hash builds the number from the same fields that equals compares.

import java.util.HashSet; import java.util.Objects; import java.util.Set; public class WithHash { public static void main(String[] args) { Set<Point> points = new HashSet<>(); points.add(new Point(1, 2)); System.out.println("contains: " + points.contains(new Point(1, 2))); System.out.println("size: " + points.size()); } } 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 other) { if (!(other instanceof Point)) { return false; } Point point = (Point) other; return x == point.x && y == point.y; } @Override public int hashCode() { return Objects.hash(x, y); } }

javac -Xlint:all WithHash.java
java WithHash

contains: true
size: 1

The equal point is found because the two equal objects now have the same hash. The set still holds one element, which is the point of a set: the second object with the same value is not added.

Rules for a correct pair

Use the same fields in both methods. Never use a mutable field that changes after the object was added to a set, because the hash would change with it and the object would be lost. Objects.hash handle the null-safe parts, and a This page is the reference for the rule in the course; the collections part returns to it when a key disappears from a map.

Exercises

  1. Add a third field to both classes and update the two methods in each. Which one forgets the field first?
  2. Add the same point twice in WithHash.java and print the size.
  3. Change contains answer now?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Object.equals compare by default?

    Answer

    The references, not the fields

    The inherited equals is identity, which is why a class with value semantics overrides it.

  2. Which two methods must agree when a class overrides equals?

    Answer

    equals and hashCode

    Equal objects must have equal hash codes, or a hash collection looks in the wrong bucket.

  3. What does a HashSet do before it calls equals?

    Answer

    It computes the hash and picks a bucket

    The hash selects a bucket, and equals is then asked only about the objects in it.

  4. What does this program print? import java.util.HashSet; import java.util.Set; public class Q1 { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("a"); set.add("a"); System.out.println(set.size()); } }

    Answer

    1

    A set holds no duplicates, and String has equals and hashCode that make the second add a no-op.

  5. What does this program print? public class Q2 { public static void main(String[] args) { Point a = new Point(1, 2); Point b = new Point(1, 2); System.out.println(a.equals(b)); } } class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } }

    Answer

    false

    The class does not override equals, so the inherited identity comparison is used.

  6. What does this program print? public class Q3 { public static void main(String[] args) { Point a = new Point(1, 2); Point b = new Point(1, 2); System.out.println(a.equals(b) + " " + (a.hashCode() == b.hashCode())); } } class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object other) { if (!(other instanceof Point)) { return false; } Point p = (Point) other; return x == p.x && y == p.y; } }

    Answer

    true false

    equals compares the fields, while the inherited hashCode is based on identity and differs.

  7. What does this program print? import java.util.Objects; public class Q4 { public static void main(String[] args) { System.out.println(Objects.hash(1, 2) == Objects.hash(1, 2)); } }

    Answer

    true

    Objects.hash is deterministic for the same arguments, which is what the contract needs.

  8. What does this program print? public class Q5 { public static void main(String[] args) { P p = new P(); System.out.println(p.equals(p)); } } class P { @Override public boolean equals(Object other) { return true; } }

    Answer

    true

    The overridden equals returns true for every argument, including the object itself.

  9. Why must hashCode use the same fields as equals?

    Answer

    Equal objects must produce the same hash

    If two equal objects hash differently, a hash collection will not find the equal one.

  10. What does this program print? import java.util.HashSet; import java.util.Set; public class Q6 { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("a"); System.out.println(set.contains(new String("a"))); } }

    Answer

    true

    String implements equals and hashCode, so the new object is found in the set.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev

Banner image