Java equals and hashCode: Why a HashSet Needs Both
== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.
What you will learn
- Explain the difference between == and equals on two Java objects
- Override equals with a null-and-class check and Objects.equals
- Explain with buckets why a HashSet needs hashCode as well as equals
- Write equals and hashCode from the same fields with Objects.hash
Before you start
- Java classes and objects
- Method overriding in Java
Here are two learners, both with id 101 and the name Asha. Ask Java asha.equals(copy) and the answer is false.
Think of identical twins: the same look, but two different people. So when are two Java objects really the same? It depends on which question you ask, and a HashSet asks two of them. Let's walk through three small programs.
== asks: is it the very same object?
Start with a class that writes neither method:
package org.studyeasy.s04l07;
public class Learner {
private int id;
private String name;
public Learner(int id, String name) {
this.id = id;
this.name = name;
}
// no equals(), no hashCode(): Learner keeps what Object gives it
}
package org.studyeasy.s04l07;
public class Ex01_DefaultEquals {
public static void main(String[] args) {
Learner asha = new Learner(101, "Asha");
Learner copy = new Learner(101, "Asha"); // a second object
Learner sameRef = asha; // the same object
System.out.println("asha == sameRef: " + (asha == sameRef));
System.out.println("asha == copy: " + (asha == copy));
boolean same = asha.equals(copy);
System.out.println("asha.equals(copy): " + same);
}
}
asha == sameRef: true
asha == copy: false
asha.equals(copy): false
asha == sameRefistrue: two variables, one object.sameRefis just a second name for Asha.asha == copyisfalse: same values, but a different object.==only asks whether it's the very same object.asha.equals(copy)is alsofalse.Learnerdoesn't write its ownequals, so it uses the one fromObject, and that version asks the same question as==.
Teach equals what "same" means
To compare values, override equals. Here's a Course with one field, its code:
package org.studyeasy.s04l07;
import java.util.Objects;
public class Course {
private String code;
public Course(String code) {
this.code = code;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Course course = (Course) o;
return Objects.equals(code, course.code);
}
// no hashCode() yet: Course keeps Object's version
}
First the class check: if o is null, or not the same class as ours, it can't be equal, so return false. Then cast it and compare the codes with Objects.equals. Same code, same course.
Now two Course objects with code JAVA101 give first.equals(copy) as true. first == copy is still false, because they are still two objects.
Take note of that last comment, though. Course has no hashCode yet.
equals says yes, the HashSet says no
package org.studyeasy.s04l07;
import java.util.HashSet;
import java.util.Set;
public class Ex02_EqualsOnly {
public static void main(String[] args) {
Course first = new Course("JAVA101");
Course copy = new Course("JAVA101");
System.out.println("equals: " + first.equals(copy));
Set<Course> courses = new HashSet<>();
courses.add(first);
courses.add(copy); // a duplicate
System.out.println("size: " + courses.size());
Course lookup = new Course("JAVA101");
System.out.println("contains: " + courses.contains(lookup));
}
}
equals: true
size: 2
contains: false
equals says the two courses are the same. A set doesn't allow duplicates, right? But the size is 2: the duplicate got in. And a brand new lookup with the same code isn't found. So equals alone isn't enough. A HashSet needs hashCode too.
Why: buckets
A HashSet starts with 16 buckets, numbered 0 to 15. When you add an object, the set asks for its hash code, and that number picks a bucket. The set only calls equals on objects inside the same bucket.
Course has no hashCode of its own, so Object gives each course its own number. For example, first might land in bucket 3 and copy in bucket 11, while lookup checks bucket 7, which is empty. These bucket numbers are only examples. They change from run to run, but the result doesn't: equal objects land in different buckets, so equals is never even asked.
The fix: equals and hashCode agree
package org.studyeasy.s04l07;
import java.util.Objects;
public class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return id == student.id && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name); // same fields as equals()
}
}
equals does the same null-and-class check, then requires both fields to match. hashCode returns Objects.hash(id, name), built from the same two fields. So the same id and the same name always give the same number.
You rarely type these by hand. In IntelliJ IDEA, press Alt+Insert, choose equals() and hashCode(), and it writes both for you.
package org.studyeasy.s04l07;
import java.util.HashSet;
import java.util.Set;
public class Ex03_EqualsAndHashCode {
public static void main(String[] args) {
Student asha = new Student(101, "Asha");
Student copy = new Student(101, "Asha");
System.out.println("asha == copy: " + (asha == copy));
System.out.println("asha.equals(copy): " + asha.equals(copy));
boolean sameHash = asha.hashCode() == copy.hashCode();
System.out.println("same hash code: " + sameHash);
System.out.println("hash code: " + asha.hashCode());
Set<Student> students = new HashSet<>();
students.add(asha);
students.add(copy); // found, so not added
System.out.println("size: " + students.size());
Student lookup = new Student(101, "Asha");
boolean found = students.contains(lookup);
System.out.println("contains: " + found);
}
}
asha == copy: false
asha.equals(copy): true
same hash code: true
hash code: 2054343
size: 1
contains: true
asha == copy is still false: they are two objects. But equals is true now, and both give the same hash code, 2054343. That number lands them both in bucket 8. When we add copy, the set finds Asha in that bucket, equals says yes, and the copy isn't added. A brand new lookup with the same values goes to bucket 8 too, so contains is true.
Run it
The project targets Java 21 in its pom.xml. Run any Ex file from IntelliJ IDEA with the green arrow next to main, or from a terminal:
javac -d out src/main/java/org/studyeasy/s04l07/*.java
java -cp out org.studyeasy.s04l07.Ex01_DefaultEquals
Common mistakes
- Overriding equals without hashCode. Exactly the
Coursebug:HashSet(andHashMapkeys) keep duplicates and can't find a copy. DeletehashCode()fromStudentand the set keeps both, size 2. - Using different fields in the two methods. If
equalscompares id and name,hashCodemust be built from id and name too, or equal objects can land in different buckets. - Comparing objects with
==.if (asha == copy)isfalseeven though both say 101 and Asha. Useequalsfor values. - Calling
name.equals(...)on a field that may be null.Objects.equals(a, b)handles null safely, which is why the examples use it.
Quick recap
| Question | Java | Asha and her copy |
|---|---|---|
| The very same object? | == | false, always: two objects |
| Same values? | equals | false by default, true once overridden |
| Which bucket? | hashCode | 2054343, bucket 8, once overridden |
| HashSet size after adding both | size() | 2 with equals only, 1 with both |
Whenever you override equals, override hashCode with the same fields.
Try it yourself
Add hashCode() to Course, built from code, and run Ex02_EqualsOnly again. What do size and contains print now?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (opens in a new tab)