Lesson 4 of 12 · 9 min · Object-oriented Java
equals, hashCode and toString
What you will learn
- The difference between
==andequals - The
equalsandhashCodecontract - Write both correctly
- See what goes wrong in
HashSetandHashMapif you skiphashCode - Why mutable fields in
hashCodeare dangerous
In simple words
If two people have the same name and the same date of birth, are they "equal"? That depends on what your program means by equal. == asks "are these literally the same object in memory?" equals asks "do these two objects represent the same thing?" Collections like HashSet need an answer to the second question, and they also use a quick number, the hash code, to find objects fast. The two must agree.
Words to know
- Identity: whether two references point to the very same object (
==). - Equality: whether two objects are considered the same by meaning (
equals). - Hash code: an integer fingerprint of an object used by hash-based collections.
- Contract: the rules that
equalsandhashCodemust follow together.
== versus equals
String a = new String("asha");
String b = new String("asha");
System.out.println(a == b); // false: two different objects
System.out.println(a.equals(b)); // true: same characters
For primitives (int, double), == compares values. For objects, == compares references. By default, Object.equals is the same as ==, so for your own classes, equals will say two customers with the same data are different unless you override it.
Customer c1 = new Customer("Asha", "Hyderabad");
Customer c2 = new Customer("Asha", "Hyderabad");
System.out.println(c1.equals(c2)); // false until you override equals
(Records get a correct equals and hashCode for free: two Order records with the same components are equal.)
The contract
When you override equals, it must be:
- Reflexive:
x.equals(x)is true. - Symmetric:
x.equals(y)is true exactly wheny.equals(x)is. - Transitive: if
x.equals(y)andy.equals(z), thenx.equals(z). - Consistent: repeated calls give the same answer while nothing changes.
- Null-safe:
x.equals(null)is false and never throws.
And the key link with hashCode:
If two objects are equal according to
equals, they must return the samehashCode.
The reverse is not required: different objects may share a hash code (a collision), but a good hash spreads values widely. Also, hashCode must give the same value for the same object while the fields used in equals do not change.
Writing them correctly
import java.util.Objects;
public final class Customer {
private final String email;
private final String name;
public Customer(String email, String name) {
this.email = email;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true; // same reference
if (!(o instanceof Customer other)) return false; // null or a different type
return Objects.equals(email, other.email); // equality is defined by email
}
@Override
public int hashCode() {
return Objects.hash(email); // same field(s) as equals
}
@Override
public String toString() {
return "Customer[email=" + email + ", name=" + name + "]";
}
}
Rules:
- Use the same fields in
equalsandhashCode. - Decide what identifies the object. A customer may be identified by email (a business key), not by every field.
- Use
Objects.equals(a, b)to compare fields (null-safe) andObjects.hash(...)to combine them. Fordouble, useDouble.compare, and for arrays,Arrays.equalsandArrays.hashCode. - Make the class
final(or think hard about subclasses): letting subclasses change equality easily breaks symmetry.instanceofis the usual check;getClass() != o.getClass()is stricter but prevents subclass equality. - Prefer a record when the object is just data:
record Customer(String email, String name) {}gives value equality over all components automatically.
IDEs can generate these methods (IntelliJ: Generate > equals() and hashCode()), and Lombok has @EqualsAndHashCode, but you must still choose the fields thoughtfully.
What breaks in HashSet and HashMap
A HashSet stores each element in a bucket chosen by its hashCode, then uses equals to compare elements in that bucket. Suppose you override equals but not hashCode:
Set<Customer> set = new HashSet<>();
set.add(new Customer("a@x.com", "Asha"));
System.out.println(set.contains(new Customer("a@x.com", "Asha"))); // probably false!
The two objects are equals, but the default hashCode (derived from the memory address) is different, so the lookup goes to a different bucket and never even calls equals. The set can then hold "duplicates", contains fails, and map.get(key) returns null for a key that is clearly there. Overriding hashCode fixes it.
The other direction: a constant hashCode (return 1;) satisfies the contract but puts everything in one bucket and turns a hash map's O(1) lookup into a slow search. A good hash code uses the same fields as equals and spreads values (the next lessons explain HashMap internals).
Mutable keys
If a field used in hashCode changes after the object is placed in a HashSet or used as a HashMap key, the object sits in the wrong bucket, and you can no longer find or remove it:
var key = new MutableKey("a");
map.put(key, 1);
key.setValue("b"); // hash changes
map.get(key); // null: the map looks in the "b" bucket
So keys should be immutable (strings, numbers, enums, records, or your own immutable classes). Do not use a mutable list or a class with setters as a map key.
Entities and databases
For JPA entities, equality is delicate: an entity's database id is null before saving. Common approaches are equality on a business key (email, order number), or on the id with careful null handling and a constant hashCode per class. Do not include lazily loaded collections in equals, hashCode or toString: they can trigger queries or infinite loops between bidirectional relationships (the JPA lessons return to this).
toString
toString() should return a readable summary for logs and debugging. Do not include secrets (passwords, tokens), and avoid printing huge collections or object cycles. Records and IDE generators write it for you.
Common mistakes
- Overriding
equalswithouthashCode. - Using different fields in the two methods.
- Comparing with
==whereequalsis meant, especially for strings and boxedIntegervalues above 127. - Mutable fields in
hashCodefor keys. - A wrong parameter type,
equals(Customer c), which overloads instead of overridingequals(Object).@Overridecatches this. - Breaking symmetry with subclasses.
Try it yourself
- Create a
Customerclass with noequals, and show that two same-data objects are not equal; then addequalsandhashCode. - Remove
hashCodeand show theHashSet.containsproblem. - Rewrite the class as a record and compare behaviour.
- Use a mutable key in a
HashMap, change it, and observegetreturningnull. - Write a test that checks reflexive, symmetric and null behaviour of your
equals.
Check yourself
What is the difference between == and equals?
== compares references (identity) for objects, while equals compares meaning as defined by the class; the default equals is the same as ==.
What is the contract between equals and hashCode?
Equal objects must have equal hash codes. Unequal objects may share a hash code, but good hashes limit collisions.
What can go wrong if you override equals but not hashCode?
Hash-based collections fail to find or deduplicate equal objects because they are placed in different buckets.
Why should map keys be immutable?
If a field used in the hash changes after insertion, the entry is in the wrong bucket and can no longer be found or removed.
Interview questions
Why must you override hashCode when you override equals?
Hash-based collections such as HashMap and HashSet use hashCode to choose a bucket and equals to match within it. Equal objects with different hash codes land in different buckets, so lookups and duplicate checks fail.
How does a record handle equals and hashCode?
The compiler generates them from all components, so two records with equal components are equal and share a hash code.
Is it legal to return a constant from hashCode?
It satisfies the contract but defeats hashing by putting everything in one bucket, so lookups degrade to linear or tree search. Use fields that match equals.
Summary
==compares references;equalscompares meaning; override it for value-like classes.- Equal objects must have equal hash codes; use the same fields in both methods and
Objects.equalsandObjects.hash. - Missing
hashCodebreaksHashSetandHashMap; mutable keys get lost. - Records generate correct
equals,hashCodeandtoString.
Going deeper
- Object.equals API documentation: the official contract.
- Object.hashCode API documentation: the matching rules.
- Objects utility class:
equals,hash,requireNonNull. - dev.java: Records: generated
equalsandhashCode.
See how much of this you can explain
A free mock interview asks you new questions on Core Java: OOP, collections and exceptions for Java Full Stack Developer and scores every answer, with what to fix.