Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Object.equals()

Compares objects by meaning. By default it works like ==, so classes override it.

Available since: Java 1.0

Syntax

public boolean equals(Object obj)

Parameters

ParameterTypeDescription
objObjectThe object to compare with; may be null.

Return value

booleantrue if the objects are considered equal.

Examples

Without an override two identical objects are not equal:

class Book {
    String title;
    Book(String title) { this.title = title; }
}
 
void main() {
    IO.println(new Book("Dune").equals(new Book("Dune")));
}

Output:

false

Overriding equals() together with hashCode():

class Book {
    final String title;
    final int year;
 
    Book(String title, int year) {
        this.title = title;
        this.year = year;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Book other)) return false;
        return year == other.year && title.equals(other.title);
    }
 
    @Override
    public int hashCode() {
        return Objects.hash(title, year);
    }
}
 
void main() {
    var a = new Book("Dune", 1965);
    var b = new Book("Dune", 1965);
    IO.println(a.equals(b));
    IO.println(new HashSet<>(List.of(a, b)).size());
}

Output:

true
1

Notes

The rule: if you override equals(), override hashCode() too, otherwise HashSet and HashMap treat equal objects as different. The parameter is Object, not your class: equals(Book other) is an overload, not an override, and collections will not call it. The @Override annotation catches this mistake.

Records (record) get correct equals() and hashCode() automatically.

See also

  • Object.hashCode() — Returns the object's hash code — a number HashMap and HashSet use to find it quickly.
  • Objects.equals() — Compares two objects with equals(), safely for null.
  • == vs equals() — == compares primitive values and object references; equals() compares object contents.
  • record — Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().

Related recipes

In the tutorial

  • Methods of the Object class — The toString, equals and hashCode methods in Java: how to override them and why equals and hashCode always change together.

Thanks for reading!

Donate to the site — we work hard for you.