Reading history

Java equals(), hashCode() and toString() Explained

6 min read 0 views

Override equals, hashCode and toString correctly in Java: == vs equals, the equals/hashCode contract, why HashSet needs both, and how records generate them.

Every Java class inherits three methods from Object that decide how its objects are compared, stored and printed: equals(), hashCode() and toString(). The versions you inherit compare memory addresses and print cryptic codes, which is rarely what you want. Getting them wrong causes some of Java’s most confusing bugs, such as a HashSet that keeps “duplicate” objects. This lesson shows the default behaviour, how to override all three correctly, and how records do it for you.

In this lesson you will learn

  • The difference between == and equals()
  • What the default methods from Object do
  • Writing a correct equals() method
  • The equals/hashCode contract and why hash collections need it
  • A readable toString(), and letting records generate all three

You should know classes and objects and HashMap.

The Default Behaviour

import java.util.HashSet;
import java.util.Set;

public class Main {
    // A class that does NOT override equals, hashCode or toString
    static class PointA {
        int x, y;
        PointA(int x, int y) { this.x = x; this.y = y; }
    }

    public static void main(String[] args) {
        PointA p1 = new PointA(2, 3);
        PointA p2 = new PointA(2, 3);
        PointA p3 = p1;

        System.out.println("p1 == p2: " + (p1 == p2));            // different objects
        System.out.println("p1 == p3: " + (p1 == p3));            // same object
        System.out.println("p1.equals(p2): " + p1.equals(p2));    // default equals is ==
        // default toString is ClassName@hexHashCode; the hex part changes from run to run
        System.out.println("toString: " + p1.toString().replaceAll("@.*", "@...."));

        Set<PointA> set = new HashSet<>();
        set.add(p1);
        set.add(p2);
        System.out.println("set size: " + set.size() + ", contains (2,3)? "
                + set.contains(new PointA(2, 3)));

        String s1 = new String("dhaka"), s2 = new String("dhaka");
        System.out.println("Strings: == " + (s1 == s2) + ", equals " + s1.equals(s2));
    }
}

Output

p1 == p2: false
p1 == p3: true
p1.equals(p2): false
toString: Main$PointA@....
set size: 2, contains (2,3)? false
Strings: == false, equals true
  • == on objects asks “are these the same object in memory?”. p1 and p2 hold equal coordinates but are two separate objects, so p1 == p2 is false. p3 is just another name for p1.
  • The equals() inherited from Object does exactly the same as ==, so it also returns false.
  • The default toString() prints the class name, @, and a hexadecimal hash code, which tells a reader almost nothing.
  • The HashSet keeps both points and cannot find a new PointA(2, 3), because, as far as Java knows, they are all different.
  • String already overrides equals() to compare characters, which is why strings must always be compared with equals(), not ==.

Overriding All Three

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class Main {
    static final class Point {
        private final int x, y;
        Point(int x, int y) { this.x = x; this.y = y; }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;                          // same object
            if (!(o instanceof Point other)) return false;       // null or another type
            return x == other.x && y == other.y;                 // compare the fields
        }

        @Override
        public int hashCode() {
            return Objects.hash(x, y);                            // equal points -> equal hash
        }

        @Override
        public String toString() {
            return "Point(" + x + ", " + y + ")";
        }
    }

    record Pixel(int x, int y) {}                                 // records generate all three

    public static void main(String[] args) {
        Point p1 = new Point(2, 3), p2 = new Point(2, 3);
        System.out.println(p1 + " equals " + p2 + ": " + p1.equals(p2));
        System.out.println("same hashCode: " + (p1.hashCode() == p2.hashCode()));
        System.out.println("equals(null): " + p1.equals(null));

        Set<Point> set = new HashSet<>();
        set.add(p1);
        set.add(p2);
        System.out.println("set size: " + set.size() + ", contains Point(2, 3)? " + set.contains(new Point(2, 3)));

        Map<Point, String> labels = new HashMap<>();
        labels.put(new Point(0, 0), "origin");
        System.out.println("lookup: " + labels.get(new Point(0, 0)));

        Pixel a = new Pixel(5, 5), b = new Pixel(5, 5);
        System.out.println(a + " equals " + b + ": " + a.equals(b));
    }
}

Output

Point(2, 3) equals Point(2, 3): true
same hashCode: true
equals(null): false
set size: 1, contains Point(2, 3)? true
lookup: origin
Pixel[x=5, y=5] equals Pixel[x=5, y=5]: true
  • A correct equals() has three steps: return true for the same object, return false for null or a different type (instanceof handles both), then compare the fields that define equality.
  • o instanceof Point other checks the type and creates the variable other in one step (pattern matching, Java 16+).
  • hashCode() must return the same number for equal objects. Objects.hash(x, y) combines the same fields used in equals.
  • Now the set holds one point and contains works, and a Point can be used as a HashMap key.
  • toString() returns something a human can read, which is what System.out.println, string concatenation and debuggers show.
  • A record generates all three methods from its components, as Pixel shows. Use a record whenever a class is mainly a carrier of data.

The equals and hashCode Contract

RuleMeaning
Reflexivex.equals(x) is true
SymmetricIf x.equals(y) then y.equals(x)
TransitiveIf x equals y and y equals z, then x equals z
ConsistentRepeated calls give the same answer while the fields do not change
Nullx.equals(null) is false, never an exception
Hash codeEqual objects must have equal hash codes (unequal objects may share one)

Hash collections first use hashCode() to pick a bucket, then equals() to compare within it. If equal objects have different hash codes, they land in different buckets and are never compared at all.

Common Mistakes

  1. Overriding equals but not hashCode, which breaks HashSet and HashMap.
  2. Writing equals(Point o) instead of equals(Object o). That overloads the method rather than overriding it; @Override catches this.
  3. Changing a field used in hashCode while the object is inside a hash set or used as a map key. The object becomes impossible to find. Make such fields final.
  4. Comparing double fields with == inside equals; use Double.compare(a, b) == 0.

Practice Exercises

Exercise 1. Write equals and hashCode for a Book class where two books are equal when their ISBN strings are equal.

Show answer
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Book other)) return false;
    return isbn.equals(other.isbn);
}

@Override
public int hashCode() {
    return isbn.hashCode();
}

Exercise 2. Replace the Point class from the second example with a record. How many lines do you save?

Show answer
record Point(int x, int y) {}

One line replaces the fields, constructor, equals, hashCode and accessors, about 20 lines. The only difference is that the record’s toString() prints Point[x=2, y=3]; override it if you want another format.

Frequently Asked Questions

Should I use instanceof or getClass() in equals?

getClass() != o.getClass() treats a subclass as never equal to its parent, which keeps equals symmetric. instanceof is simpler and is safe when the class is final, as in the example. Many IDEs can generate either version.

Can my IDE generate these methods?

Yes. IntelliJ IDEA, Eclipse and VS Code can all generate equals, hashCode and toString from the fields you choose. For data classes, a record is even simpler.

Summary

  • == compares references; equals() should compare meaning.
  • Always override equals and hashCode together, using the same fields.
  • Override toString for readable output and debugging.
  • Records generate all three automatically.

Next: Java Scanner: Reading User Input.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *