Sub topic 8
How Java Decides Two Objects Are Equal
Before you can use sets and maps well, you need to know how Java decides that two objects are "the same." Lists use this rule to find elements. Sets use it to block duplicates. Maps use it to find keys. If you get the rule wrong, your collections will act in strange ways and no error message will tell you why.
This chapter covers two methods, equals and hashCode. Every Java object has both of them.
Two Kinds of "Same"
Java has two ways to compare objects.
- Identity means "the same object in memory." The
==operator checks identity. - Equality means "objects with the same meaning or the same data." The
equalsmethod checks equality.
Think of two printed copies of the same book. They are two separate objects, so they do not have the same identity. They hold the same words, so they are equal in meaning.
Here is the difference in code:
public class EqualityDemo {
static class Card {
String suit;
int rank;
Card(String suit, int rank) {
this.suit = suit;
this.rank = rank;
}
}
public static void main(String[] args) {
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false: two different objects
System.out.println(a.equals(b)); // true: same characters
Card c1 = new Card("hearts", 5);
Card c2 = new Card("hearts", 5);
System.out.println(c1 == c2); // false
System.out.println(c1.equals(c2)); // false: Card has no equals of its own
}
}String comes with its own equals method that compares characters. Card does not have one, so it gets the default method from Object. Object is the class that every other class extends. The default equals is just == again, so two cards with the same suit and rank still count as different.
Why Collections Care
Collection methods call equals for you. List.contains, List.indexOf, and List.remove(Object) all walk through the list and call equals on each element. If your class has no equals, these methods can only find the exact same object you put in.
import java.util.ArrayList;
import java.util.List;
public class ContainsDemo {
static class Card {
String suit;
int rank;
Card(String suit, int rank) {
this.suit = suit;
this.rank = rank;
}
}
public static void main(String[] args) {
List<Card> hand = new ArrayList<>();
hand.add(new Card("spades", 1));
System.out.println(hand.contains(new Card("spades", 1))); // false
}
}The hand holds the ace of spades, but contains says no. To fix this, you override equals, which means you write your own version that replaces the default one.
Writing equals
A good equals method has four steps:
- If the other object is the same object (
this == o), returntrue. - If the other object is not the right type, or it is
null, returnfalse. - Cast the other object to your class.
- Compare the fields that define "sameness."
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Book {
private final String title;
private final String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Book)) return false; // also false when o is null
Book other = (Book) o;
return Objects.equals(title, other.title)
&& Objects.equals(author, other.author);
}
@Override
public int hashCode() {
return Objects.hash(title, author);
}
public static void main(String[] args) {
List<Book> shelf = new ArrayList<>();
shelf.add(new Book("Dune", "Herbert"));
System.out.println(shelf.contains(new Book("Dune", "Herbert"))); // true
}
}Some details are worth knowing:
- The parameter type must be
Object, notBook. If you writeequals(Book o), you create a new method instead of replacing the old one, and collections will never call it. The@Overrideannotation catches this mistake, because the compiler reports an error if nothing is being replaced. Objects.equals(x, y)compares two values safely even if one of them isnull.instanceofreturnsfalsefornull, so step 2 also handles the null case.
The equals Contract
A contract is a set of rules that a method promises to follow. Collections assume your equals obeys these rules:
| Rule | Meaning |
|---|---|
| Reflexive | `x.equals(x)` is always `true` |
| Symmetric | If `x.equals(y)` is true, then `y.equals(x)` is true |
| Transitive | If `x` equals `y` and `y` equals `z`, then `x` equals `z` |
| Consistent | Calling it again gives the same answer if nothing changed |
| Null-safe | `x.equals(null)` is always `false` |
If you compare the same fields in the same way, as Book does, you follow all five rules without extra work.
What hashCode Does
A hash code is an int that an object computes from its data. Hash-based collections such as HashSet and HashMap use it to jump straight to a small group of candidates, called a bucket, instead of checking every element. You will learn these collections in later chapters. For now, the lookup works like this:
The collection looks only in the bucket chosen by the hash code. If two equal objects produce different hash codes, the collection searches the wrong bucket and never calls equals on the right object.
That leads to the most important rule in this chapter:
The opposite does not have to be true. Two unequal objects may share a hash code. This is called a collision. Collisions are allowed. They only slow lookups down a little, because the collection has to call equals on more objects in the bucket.
Objects.hash(title, author) is an easy way to write a correct hashCode. It combines the hash codes of the fields you pass in.
What Goes Wrong Without hashCode
Suppose you override only equals:
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class HalfDone {
static class Tag {
String name;
Tag(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Tag)) return false;
return Objects.equals(name, ((Tag) o).name);
}
// no hashCode override
}
public static void main(String[] args) {
Set<Tag> tags = new HashSet<>();
tags.add(new Tag("java"));
tags.add(new Tag("java"));
System.out.println(tags.size()); // usually 2, not 1
}
}The default hashCode gives each object its own number, so the two tags almost always land in different buckets. The set never compares them with equals, and it keeps a "duplicate."
Gotcha: Changing a Key After Adding It
The hash code is computed when you add the object. If you later change a field that hashCode uses, the object stays in its old bucket while its new hash code points to a different one.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class MutableKeyDemo {
static class Student {
int id;
Student(int id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
return id == ((Student) o).id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
public static void main(String[] args) {
Set<Student> students = new HashSet<>();
Student s = new Student(1);
students.add(s);
s.id = 2; // changes the hash code
System.out.println(students.contains(s)); // false
System.out.println(students.size()); // 1: it is still inside
}
}The set still holds the student, but it can no longer find it. The safest fix is to make the fields used by equals and hashCode final, as Book does, so they cannot change.
A Shortcut: Records
From Java 16 on, a record is a short way to declare a class that just holds data. Java writes equals, hashCode, and toString for you, based on all the fields. The fields are also final.
import java.util.HashSet;
import java.util.Set;
public class RecordDemo {
record Point(int x, int y) {}
public static void main(String[] args) {
Set<Point> points = new HashSet<>();
points.add(new Point(1, 2));
points.add(new Point(1, 2));
System.out.println(points.size()); // 1
System.out.println(new Point(1, 2).equals(new Point(1, 2))); // true
}
}Most IDEs can also generate equals and hashCode for an ordinary class. Use that feature and check which fields it includes.
Quick Checklist
- Use
equals, not==, to compare values. - Declare the method as
equals(Object o)and add@Override. - Override
hashCodewhenever you overrideequals. - Build both from the same fields.
- Keep those fields final if objects go into sets or serve as map keys.
Exercise
A class Coin overrides equals to compare its value field but does not override hashCode. You add new Coin(5) to a List and to a HashSet, then call contains(new Coin(5)) on each. What does each call most likely return, and why?
Show answer
The list returns true, because List.contains calls equals on each element. The set most likely returns false. HashSet uses hashCode first to pick a bucket, and the default hashCode gives the two coins different numbers, so the set looks in the wrong bucket and never calls equals on the stored coin.
Exercise
A programmer writes public boolean equals(Coin other) without @Override. Why does list.contains(new Coin(5)) still return false?
Show answer
The method takes a Coin parameter instead of Object, so it overloads equals and does not override it. Collections call equals(Object), which is still the default identity check. Adding @Override would have turned this mistake into a compile error.
Exercise
Is this hashCode legal for the Book class: public int hashCode() { return 42; }? Is it a good idea?
Show answer
It is legal, because equal books always return the same hash code, so the contract holds. It is a bad idea, because every book lands in the same bucket. Every lookup then has to call equals on every element, which makes hash-based collections as slow as searching a list.