Skip to content

Module 7 · Core Java APIs — topic 3 of 4

equals, hashCode and toString

The methods every class inherits from Object, how to override equals and hashCode correctly together, why it matters for HashSet and HashMap, and the Objects helper class.

Beginner 16 min read·Lesson 25 of 39 in Java Programming

Learning objectives

  • Override equals following its contract
  • Override hashCode consistently with equals
  • Use java.util.Objects helpers

Definition

java.lang.Object is the root of every class. Its methods equals (logical equality), hashCode (an integer used by hash-based collections) and toString (a text description) are meant to be overridden; equal objects must always have equal hash codes.

Introduction

Two Point objects with the same coordinates should probably be 'equal', but Java can't know that unless you say so. By default equals is identity (==) and hashCode is based on the object's identity. For value-like classes you must override both — and they must agree, or HashSet and HashMap stop working.

Why it matters

HashMap and HashSet — the most used collections — rely completely on equals and hashCode.

A broken equals/hashCode pair causes 'impossible' bugs: an object you just added to a set can't be found.

Detailed explanation

toString() returns ClassName@hexHash by default. Override it to show the important fields.

The equals contract. It must be *reflexive* (x.equals(x)), *symmetric*, *transitive*, *consistent* (same answer while fields don't change) and return false for null. The parameter type must be Object, otherwise you overload instead of override.

A standard equals. Return true for the same reference; return false if the argument is null or of a different class; cast and compare the significant fields — primitives with ==, objects with Objects.equals (null-safe), doubles with Double.compare.

The hashCode contract. Equal objects must have equal hash codes. Unequal objects may share a hash code, but fewer collisions mean faster maps. The easiest correct implementation is Objects.hash(field1, field2, ...).

Why both. A HashSet first uses hashCode to pick a bucket, then equals to compare within it. Override only equals and two equal objects may land in different buckets, so contains fails.

Mutable keys. If a field used in hashCode changes while the object is inside a HashSet or used as a HashMap key, the object becomes unfindable. Use immutable fields for equality — records do this automatically.

Other Object methods include getClass(), and the thread-related wait/notify. finalize is deprecated; use try-with-resources for clean-up.

Syntax

Java
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}
@Override
public int hashCode() { return Objects.hash(x, y); }
@Override
public String toString() { return "(" + x + ", " + y + ")"; }
  • equals must take Object, not your class.
  • Use the same fields in equals and hashCode.
  • Objects.equals(a, b) handles nulls safely.

Code examples

Default behaviour versus overriding

Java
import java.util.Objects;
public class Main {
public static void main(String[] args) {
Plain a = new Plain(1, 2), b = new Plain(1, 2);
System.out.println("Plain equal? " + a.equals(b) + ", toString starts with: " + a.toString().startsWith("Plain@"));
Point p = new Point(1, 2), q = new Point(1, 2), r = new Point(2, 1);
System.out.println("Point equal? " + p.equals(q) + " " + p.equals(r) + " " + p.equals(null));
System.out.println("same hash: " + (p.hashCode() == q.hashCode()) + ", toString: " + p);
}
}
class Plain {
final int x, y;
Plain(int x, int y) { this.x = x; this.y = y; }
}
class Point {
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;
if (o == null || getClass() != o.getClass()) return false;
Point other = (Point) o;
return x == other.x && y == other.y;
}
@Override public int hashCode() { return Objects.hash(x, y); }
@Override public String toString() { return "(" + x + ", " + y + ")"; }
}
Output
Plain equal? false, toString starts with: true
Point equal? true false false
same hash: true, toString: (1, 2)

Objects helpers

Java
import java.util.Objects;
public class Main {
public static void main(String[] args) {
String a = null, b = "x";
System.out.println(Objects.equals(a, b) + " " + Objects.equals(null, null));
System.out.println(Objects.toString(a, "(none)") + " " + Objects.requireNonNullElse(a, "default"));
System.out.println(Objects.hash(1, "a") == Objects.hash(1, "a"));
try {
Objects.requireNonNull(a, "name must not be null");
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
Output
false true
(none) default
true
name must not be null

More examples

What goes wrong in a HashSet without hashCode

Java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<BadKey> bad = new HashSet<>();
bad.add(new BadKey("CS101"));
System.out.println("bad contains equal key: " + bad.contains(new BadKey("CS101")));
bad.add(new BadKey("CS101"));
System.out.println("bad size after adding a duplicate: " + bad.size());
Set<GoodKey> good = new HashSet<>();
good.add(new GoodKey("CS101"));
System.out.println("good contains equal key: " + good.contains(new GoodKey("CS101")));
good.add(new GoodKey("CS101"));
System.out.println("good size after adding a duplicate: " + good.size());
MutableKey m = new MutableKey("A");
Set<MutableKey> set = new HashSet<>();
set.add(m);
m.code = "B"; // changes the hash code while inside the set
System.out.println("mutable key still found: " + set.contains(m));
}
}
class BadKey { // equals without hashCode
final String code;
BadKey(String code) { this.code = code; }
@Override public boolean equals(Object o) { return o instanceof BadKey k && k.code.equals(code); }
}
class GoodKey {
final String code;
GoodKey(String code) { this.code = code; }
@Override public boolean equals(Object o) { return o instanceof GoodKey k && k.code.equals(code); }
@Override public int hashCode() { return code.hashCode(); }
}
class MutableKey {
String code;
MutableKey(String code) { this.code = code; }
@Override public boolean equals(Object o) { return o instanceof MutableKey k && Objects.equals(k.code, code); }
@Override public int hashCode() { return Objects.hashCode(code); }
}
Output
bad contains equal key: false
bad size after adding a duplicate: 2
good contains equal key: true
good size after adding a duplicate: 1
mutable key still found: false

Step-by-step explanation

  • BadKey overrides equals but not hashCode, so two equal keys usually get different identity-based hash codes and land in different buckets.
  • That is why contains fails and a 'duplicate' is accepted, breaking the rule that a set holds no duplicates.
  • GoodKey bases hashCode on the same field as equals, so the set behaves correctly.
  • o instanceof GoodKey k && ... is a compact equals using pattern matching; it also returns false for null.
  • Changing m.code after insertion changes its hash code, so the set looks in the wrong bucket and can no longer find the object — use immutable fields as keys.

Expected output

Running “What goes wrong in a HashSet without hashCode” prints exactly:

TextOutput
bad contains equal key: false
bad size after adding a duplicate: 2
good contains equal key: true
good size after adding a duplicate: 1
mutable key still found: false

Practical applications

  • Entity and value classes used as HashMap keys or stored in HashSets
  • De-duplicating records loaded from files or databases
  • Unit tests that compare expected and actual objects with assertEquals

Best practices

  • Override equals and hashCode together, using the same fields.
  • Base equality on immutable fields.
  • Let your IDE generate them, or use a record.

Common mistakes

Wrong equals signature

Avoid

public boolean equals(Point other) { ... }

Prefer

@Override
public boolean equals(Object other) { ... }

Taking Point creates an overload; collections call equals(Object), which still uses identity.

Overriding equals but not hashCode

Avoid

@Override public boolean equals(Object o) { ... } // no hashCode

Prefer

@Override public boolean equals(Object o) { ... }
@Override public int hashCode() { return Objects.hash(...); }

Equal objects would have different hash codes, breaking HashMap and HashSet.

Important notes

  • getClass() != o.getClass() makes subclasses unequal to their parents; instanceof allows them — choose deliberately and keep equals symmetric.
  • Records automatically implement equals, hashCode and toString from their components.

Key takeaways

  • equals defines logical equality and must accept Object.
  • Equal objects must have equal hash codes; use Objects.hash.
  • Mutable fields used in hashCode break hash-based collections.

Try it yourself

  1. 1
    Write equals and hashCode for a Book identified by its ISBN, and prove a HashSet removes duplicates.
  2. 2
    Show that a TreeSet uses compareTo rather than equals by giving a class inconsistent methods.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

6 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerIf you override equals, what must you also override?
  • BeginnerWhich signature correctly overrides Object.equals?
  • ModerateWhat is printed?
Practise this topic