Sub topic 8
How Java Decides Two Objects Are Equal
Sets and maps need to know when two objects count as "the same." A set keeps only one copy of each element. A map keeps only one value per key. Java answers the "same or not" question with two methods that every object has: equals and hashCode. This chapter shows how those methods work, so the set and map chapters that come next make sense.
Two kinds of "equal"
Java can compare objects in two ways:
==checks identity. Identity means "are these the exact same object in memory?"equalschecks equality. Equality means "do these objects hold the same meaningful data?"
Every class inherits equals from Object. Unless a class overrides it, equals behaves just like ==. So two Book objects with the same title and year are not equal unless you write your own equals method that compares those fields.
What hashCode is for
A hash code is an int that an object computes from its data. HashSet and HashMap use it to sort objects into buckets, which are small groups, so they can find things fast. When they look something up, they first go to the bucket that matches the hash code. Then they call equals only on the few objects inside that bucket.
The diagram explains why the two methods must agree. Suppose two equal objects had different hash codes. The collection would search the wrong bucket, never call equals, and miss the match.
Writing equals and hashCode
This class compares books by title and year:
import java.util.Objects;
public class Book {
private final String title;
private final int year;
public 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)) return false;
Book other = (Book) o;
return year == other.year && title.equals(other.title);
}
@Override
public int hashCode() {
return Objects.hash(title, year);
}
public static void main(String[] args) {
Book a = new Book("Dune", 1965);
Book b = new Book("Dune", 1965);
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // true
}
}Objects.hash is a helper method. It builds a hash code from the fields you pass to it. Pass it the same fields that equals compares.
The contract
The contract is the set of rules these two methods must follow:
| Rule | Meaning |
|---|---|
| Equal objects, equal hash codes | If `a.equals(b)` is true, `a.hashCode()` must equal `b.hashCode()`. |
| Same hash code is allowed for different objects | Two unequal objects can share a hash code. This is called a collision. |
| Consistent results | Calling the methods again gives the same answer if the fields haven't changed. |
| Symmetric | If `a.equals(b)` is true, then `b.equals(a)` must also be true. |
Exercise
A class Student overrides equals to compare id fields but does not override hashCode. You add two Student objects with the same id to a HashSet. What is the likely size of the set, and why?
Show answer
The size is likely 2. Without an override, hashCode comes from Object and is based on identity, so the two students usually land in different buckets. The set never calls equals on them and keeps both.
Exercise
Two different Book objects return the same hashCode but equals returns false. Is this a bug?
Show answer
No. This is a collision, and the contract allows it. The collection puts both books in the same bucket and uses equals to tell them apart. Many collisions slow lookups down, but the results are still correct.