JAVA-102 · Lesson 10 of 12 · 23 min
The Object class: equals, hashCode and toString
▶ Video coming soon A video version of this lesson is on the way.
Hamza's test of the booking system on a practice weekend turned up a puzzle, as Ingrid predicted it would. He kept the customers in a set so that each person appeared once, yet Ana Ruiz appeared twice: once from the repair booking and once from the rental. The two Customer objects held the same name and phone number. The plan for Wednesday, March 24, 2027 is the explanation, which lies in a class every Java class extends without saying so, Object, and in three of its methods: equals, hashCode and toString.
Every class extends Object
A class declared without extends implicitly extends java.lang.Object, and every other class extends it through its superclasses. So every object, of any class, has Object's methods. The three that matter most are toString, which turns an object into text, equals, which says whether two objects should be considered equal, and hashCode, which returns a number used by hash-based collections. Object's own versions are simple: toString prints the class name and a hexadecimal code, and equals is the same as ==, identity.
public class Main {
public static void main(String[] args) {
Customer a = new Customer("Ana Ruiz", "905-555-0142");
Customer b = new Customer("Ana Ruiz", "905-555-0142");
Object o = a;
System.out.println("a.equals(b): " + a.equals(b));
System.out.println("a.equals(a): " + a.equals(a));
System.out.println("o is the same object as a: " + (o == a));
System.out.println("toString starts with: " + a.toString().substring(0, 9));
System.out.println("Class: " + a.getClass().getSimpleName());
}
}
class Customer {
private final String name;
private final String phone;
Customer(String name, String phone) {
this.name = name;
this.phone = phone;
}
}a.equals(b): false a.equals(a): true o is the same object as a: true toString starts with: Customer@ Class: Customer
What this code does
Customer does not override equals, so it inherits Object's version, which compares identity: a and b hold the same details but are different objects, so equals is false. Any object can be held in a variable of type Object. The inherited toString begins with the class name followed by an at sign and a code, and getClass reports the object's actual class.
Because Object's toString includes a code that changes from run to run, the example prints only its first nine characters, Customer@. Without your own toString, that code is what a printed object shows, which is why every class in this course has overridden toString since JAVA-101.
Overriding toString
A good toString returns a short, readable description that helps in printouts and, above all, in debugging. It should include the fields that identify the object, need not include everything, and must never throw. Mark it with @Override and make it public, because Object declares it public.
For records, Java generates a toString such as Slot[date=2027-04-03, hour=9], which is usually good enough for debugging. You can still override it in a record when the screen or a receipt needs a friendlier form.
The equals contract
Overriding equals lets a class define when two objects mean the same thing. Customers with the same phone number are the same person, at least for the shop's purposes. But equals is used by the whole Java library, by collections and by sorting, so it must follow a contract of five rules. For any non-null references x, y and z:
| Rule | Meaning |
|---|---|
| Reflexive | x.equals(x) is true |
| Symmetric | x.equals(y) is true exactly when y.equals(x) is true |
| Transitive | if x.equals(y) and y.equals(z), then x.equals(z) |
| Consistent | repeated calls give the same answer while the objects do not change |
| Non-null | x.equals(null) is false and never throws |
The standard way to write equals checks three things in order: whether the other reference is the same object, whether it is an object of the right class, and whether the significant fields are equal. Java 16's pattern matching for instanceof makes the middle step short.
import java.util.Objects;
public class Main {
public static void main(String[] args) {
Customer a = new Customer("Ana Ruiz", "905-555-0142");
Customer b = new Customer("Ana R.", "905-555-0142");
Customer c = new Customer("Ana Ruiz", "905-555-0199");
System.out.println("a equals b: " + a.equals(b));
System.out.println("b equals a: " + b.equals(a));
System.out.println("a equals c: " + a.equals(c));
System.out.println("a equals null: " + a.equals(null));
System.out.println("a equals a String: " + a.equals("905-555-0142"));
}
}
final class Customer {
private final String name;
private final String phone;
Customer(String name, String phone) {
this.name = name;
this.phone = phone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Customer other)) return false;
return phone.equals(other.phone);
}
@Override
public int hashCode() {
return Objects.hash(phone);
}
@Override
public String toString() {
return name + " (" + phone + ")";
}
}a equals b: true b equals a: true a equals c: false a equals null: false a equals a String: false
What this code does
equals takes an Object parameter, so it overrides Object's equals, and it first checks for the same object, then for a Customer, then compares phone numbers. Two customers with the same phone are equal even if the name was typed differently, and the test works the same in both directions. A null or a String is never equal to a Customer, and the instanceof test handles null without throwing.
Two details deserve attention. The parameter must be of type Object: a method equals(Customer other) would overload, not override, and collections would never call it. And Customer is final, which avoids a subtle problem with subclasses breaking symmetry; when a class may be extended, equals needs more care, and many designers simply make value-like classes final or use records.
public class Main {
public static void main(String[] args) {
System.out.println("never runs");
}
}
final class Customer {
private final String phone;
Customer(String phone) { this.phone = phone; }
@Override
public boolean equals(Customer other) {
return phone.equals(other.phone);
}
}What this code does
The parameter type is Customer instead of Object, so this method does not override Object's equals; it is a new overload. Because it is marked @Override, javac reports the mistake instead of letting it slip through. Without the annotation, the class would compile and every collection would keep using identity.
$ javac Main.java
Main.java:11: error: method does not override or implement a method from a supertype
@Override
^
1 errorhashCode and why it must agree with equals
The second half of the contract links two methods: objects that are equal must have equal hash codes. Unequal objects may share a hash code, though fewer collisions are better. A hash code is an int computed from an object's significant fields. Hash-based collections such as HashSet and HashMap, which JAVA-120 covers, use it to decide which bucket to store an object in, and they compare with equals only within one bucket. If equal objects had different hash codes, the collection would look in the wrong bucket and never find the match.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<GoodCustomer> good = new HashSet<>();
good.add(new GoodCustomer("905-555-0142"));
good.add(new GoodCustomer("905-555-0142"));
System.out.println("With hashCode: " + good.size() + " customer(s)");
Set<BadCustomer> bad = new HashSet<>();
bad.add(new BadCustomer("905-555-0142"));
bad.add(new BadCustomer("905-555-0142"));
System.out.println("Without hashCode: " + bad.size() + " customer(s)");
}
}
final class GoodCustomer {
private final String phone;
GoodCustomer(String phone) { this.phone = phone; }
@Override public boolean equals(Object o) {
return o instanceof GoodCustomer g && phone.equals(g.phone);
}
@Override public int hashCode() { return Objects.hash(phone); }
}
final class BadCustomer {
private final String phone;
BadCustomer(String phone) { this.phone = phone; }
@Override public boolean equals(Object o) {
return o instanceof BadCustomer b && phone.equals(b.phone);
}
// hashCode not overridden: Object's version is based on identity
}With hashCode: 1 customer(s) Without hashCode: 2 customer(s)
What this code does
Both classes have the same equals, but only GoodCustomer overrides hashCode. The set of GoodCustomer finds the second object equal to the first and keeps one, while the set of BadCustomer puts the two objects in different buckets and keeps both. That is exactly the duplicate Ana Ruiz from Hamza's test.
A HashSet is a collection that keeps no duplicates, and Set<GoodCustomer> means a set of GoodCustomer objects; JAVA-120 explains collections and these angle-bracket types in full. The lesson here is the rule: whenever you override equals, override hashCode too, using the same fields.
Writing hashCode
The simplest correct hashCode passes the same fields used in equals to Objects.hash, which combines them. For speed-sensitive code, the classic hand-written form multiplies by 31 and adds each field's hash. Both are consistent with equals as long as they use exactly the fields equals compares, and no others.
import java.util.Objects;
public class Main {
public static void main(String[] args) {
Slot a = new Slot("2027-04-03", 9);
Slot b = new Slot("2027-04-03", 9);
Slot c = new Slot("2027-04-03", 10);
System.out.println("a equals b: " + a.equals(b) + ", same hash: " + (a.hashCode() == b.hashCode()));
System.out.println("a equals c: " + a.equals(c) + ", same hash: " + (a.hashCode() == c.hashCode()));
System.out.println("Objects.hash matches hand-written: " + (a.hashCode() == a.handHash()));
}
}
final class Slot {
private final String date;
private final int hour;
Slot(String date, int hour) {
this.date = date;
this.hour = hour;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
return o instanceof Slot s && hour == s.hour && date.equals(s.date);
}
@Override
public int hashCode() {
return Objects.hash(date, hour);
}
int handHash() {
int h = 1;
h = 31 * h + date.hashCode();
h = 31 * h + Integer.hashCode(hour);
return h;
}
}a equals b: true, same hash: true a equals c: false, same hash: false Objects.hash matches hand-written: true
What this code does
equals compares the date and the hour, and hashCode combines exactly those two fields with Objects.hash. Equal slots therefore always share a hash code, while slots that differ by an hour very likely do not. handHash shows the 31-multiplier formula that Objects.hash uses inside, which gives the same number.
A hash code must not depend on fields that can change while the object is stored in a hash-based collection, or the object becomes lost inside it. This is one more reason to base equality on fields that never change, such as a final phone number or booking number, or to use immutable records.
Records do it for you
A record generates equals, hashCode and toString from all of its components, following the contracts exactly. For data carriers this removes a whole category of bugs. If equality should use only some fields, for example customers equal by phone alone, the record can override equals and hashCode, but at that point an ordinary final class is often clearer.
import java.util.HashSet;
import java.util.Set;
public class Main {
record Customer(String name, String phone) { }
public static void main(String[] args) {
Set<Customer> customers = new HashSet<>();
customers.add(new Customer("Ana Ruiz", "905-555-0142"));
customers.add(new Customer("Ana Ruiz", "905-555-0142"));
customers.add(new Customer("Theo Park", "905-555-0177"));
System.out.println("Distinct customers: " + customers.size());
System.out.println(new Customer("Ana Ruiz", "905-555-0142"));
}
}Distinct customers: 2 Customer[name=Ana Ruiz, phone=905-555-0142]
What this code does
The record's generated equals and hashCode use both components, so the two identical Ana Ruiz records count as one in the set. The generated toString shows both components with their names. No methods had to be written at all.
equals for entities with an identity
Not every class should define equality by its values. A Booking is an entity: it has an identity, its booking number, that stays the same while its status and notes change. Two bookings with identical details on the same day are still two bookings. For an entity, either keep Object's identity-based equals, or define equals on the unchanging identifier alone. Value-like classes, such as Money, Slot and Customer contact details, compare by their values.
| Kind of class | Example | equals should compare |
|---|---|---|
| Value | Money, Slot, a phone number | All significant values; best as a record or final class |
| Entity with an id | Booking with a booking number | Only the id, which never changes |
| Entity without an id | An open Till | Identity; do not override equals |
import java.util.Objects;
public class Main {
public static void main(String[] args) {
Booking a = new Booking(1042, "Ana Ruiz");
Booking sameRecord = new Booking(1042, "Ana Ruiz");
Booking other = new Booking(1043, "Ana Ruiz");
sameRecord.confirm();
System.out.println("Same booking number, different status: " + a.equals(sameRecord));
System.out.println("Same details, different number: " + a.equals(other));
System.out.println(a + " / " + sameRecord);
}
}
final class Booking {
private final int number;
private final String customer;
private String status = "REQUESTED";
Booking(int number, String customer) {
this.number = number;
this.customer = customer;
}
void confirm() { status = "CONFIRMED"; }
@Override
public boolean equals(Object o) {
return o instanceof Booking b && number == b.number;
}
@Override
public int hashCode() {
return Integer.hashCode(number);
}
@Override
public String toString() {
return "#" + number + " " + customer + " " + status;
}
}Same booking number, different status: true Same details, different number: false #1042 Ana Ruiz REQUESTED / #1042 Ana Ruiz CONFIRMED
What this code does
Booking defines equality by its booking number alone, which never changes, so two objects for booking 1042 are equal even when one has been confirmed. Two bookings with the same customer but different numbers are different bookings. hashCode uses only the number, matching equals.
Here two objects for booking 1042 might arise when the same booking is loaded twice from a database, which JAVA-250 does. Equality by id makes them count as the same booking, which is what the shop means.
Try it yourself
equals and hashCode for a value
Override equals and hashCode in Part so two parts are equal when they have the same code, ignoring the name.
The program should print true, false and Set size: 2.
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Part a = new Part("A-02", "700x25c tube");
Part b = new Part("A-02", "inner tube 700c");
Part c = new Part("B-11", "brake pads");
System.out.println(a.equals(b));
System.out.println(a.equals(c));
Set<Part> set = new HashSet<>();
set.add(a); set.add(b); set.add(c);
System.out.println("Set size: " + set.size());
}
}
final class Part {
private final String code;
private final String name;
Part(String code, String name) {
this.code = code;
this.name = name;
}
}Try it yourself
A useful toString
Override toString in Rental so a rental prints as Rental #77: Theo Park, CARGO, 3 days.
The program should print that line and then Rental #78: Mei Lin, CITY, 1 day (note the singular).
public class Main {
enum Type { CITY, CARGO, TANDEM }
public static void main(String[] args) {
System.out.println(new Rental(77, "Theo Park", Type.CARGO, 3));
System.out.println(new Rental(78, "Mei Lin", Type.CITY, 1));
}
record Rental(int number, String customer, Type type, int days) { }
}Common mistakes
MistakeWriting equals(Customer other) instead of equals(Object o).
InsteadTake an Object parameter so the method overrides Object's equals; @Override catches the mistake.
MistakeOverriding equals but not hashCode.
InsteadAlways override both, using the same fields, or hash-based collections will keep duplicates.
MistakeBasing equals on fields that change, such as a booking's status.
InsteadUse values that never change, such as an id, or make the class immutable.
MistakeLetting equals throw when given null.
InsteadReturn false for null; instanceof does this automatically.
MistakeHand-writing equals, hashCode and toString for a simple data carrier.
InsteadUse a record, which generates all three correctly.
Summary and key terms
- Every class extends Object and inherits toString, equals and hashCode.
- Object's equals compares identity and its toString prints the class name and a code, so useful classes override them. equals must be reflexive, symmetric, transitive, consistent and false for null; it takes an Object parameter, checks for the same object, checks the type with instanceof and compares significant fields.
- Objects that are equal must have equal hash codes, so whenever equals is overridden, hashCode must be overridden with the same fields, usually with Objects.hash; otherwise HashSet and HashMap keep duplicates.
- Hash codes should not depend on fields that change.
- Records generate all three methods from their components.
- Value classes compare by their values; entities with an identity, such as a booking with a number, compare by that unchanging id or keep identity-based equality.
- Object
- The class at the top of Java's class hierarchy, which every class extends.
- toString
- The method that returns a text description of an object.
- equals
- The method that decides whether two objects should be considered equal.
- equals contract
- The rules an equals method must follow: reflexive, symmetric, transitive, consistent and false for null.
- Hash code
- An int computed from an object's fields, used to place it in hash-based collections.
- hashCode
- The method that returns an object's hash code; equal objects must return equal values.
- Objects.hash
- A helper that combines several values into one hash code.
- HashSet
- A collection that keeps no duplicates, using hashCode and equals.
- Value object
- An object defined entirely by its values, such as Money or a time slot.
- Entity
- An object with an identity that stays the same while its state changes.
Practice problems
Work each problem on paper first, then reveal the answer to check.
What does Object's equals compare?
Show answer
Identity, the same as ==.
Why must equals take an Object parameter?
Show answer
Otherwise it overloads rather than overrides, and collections never call it.
What goes wrong if equals is overridden but hashCode is not?
Show answer
Equal objects get different hash codes, so a HashSet can keep duplicates.
Which fields should hashCode use?
Show answer
Exactly the fields equals compares.
Should two Booking objects with the same booking number be equal?
Show answer
Yes, if equality is by the unchanging id; their status may differ.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.