🚀 Purpose of the hashCode()
Method in Java
The hashCode()
method returns an integer (hash code) for an object. This hash code is used by hash-based collections like HashMap
, HashSet
, and HashTable
to efficiently store and retrieve objects.
1️⃣ Why Do We Need hashCode()
?
In Java, hashCode()
is used to:
- Optimize Performance in Hash-Based Collections (
HashSet
,HashMap
,HashTable
). - Ensure Correct Functionality when overriding
equals()
. - Speed Up Lookups and Inserts by reducing comparisons.
Without hashCode()
, Performance Would Be Slow!
If Java only used equals()
to compare objects, searching for an element in a HashMap
would take O(n) time complexity (linear search).
With hashCode()
, it only takes O(1) on average (constant time).
2️⃣ How Does hashCode()
Work in Hash-Based Collections?
When an object is used as a key in a HashMap
or stored in a HashSet
:
- Java Calls
hashCode()
to determine the hash bucket (array index). - If Multiple Objects Have the Same Hash Code (Collision), It Uses
equals()
to check for equality. - If
equals()
Returnstrue
, The Object Is Considered the Same; otherwise, it is stored separately.
🔹 Example: Using a HashMap
Without Overriding hashCode()
import java.util.HashMap;
import java.util.Map;
class Person {
String name;
public Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return name.equals(person.name);
}
// ❌ No hashCode() override!
}
public class Main {
public static void main(String[] args) {
Map<Person, String> map = new HashMap<>();
Person p1 = new Person("Alice");
map.put(p1, "Developer");
Person p2 = new Person("Alice"); // Different object, but logically equal
System.out.println(map.get(p2)); // ❌ Expected: "Developer", but prints: null
}
}
🔴 What Went Wrong?
p1.equals(p2)
istrue
(same name).- But
p1.hashCode()
is different fromp2.hashCode()
, soHashMap
searches in the wrong bucket. - Lookup fails because
hashCode()
was not overridden.
3️⃣ What Happens If hashCode()
is Not Overridden?
🚨 Violating the equals()
–hashCode()
Contract 🚨
- If
equals()
says two objects are equal, they must have the same hash code. - If
hashCode()
is not overridden,HashSet
andHashMap
may store duplicates or fail lookups.
4️⃣ Correctly Overriding hashCode()
To fix the issue, we must override hashCode()
whenever equals()
is overridden.
✅ Fixed Version
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
class Person {
private String name;
public Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name); // ✅ Includes "name" field in hashCode()
}
}
public class Main {
public static void main(String[] args) {
Map<Person, String> map = new HashMap<>();
Person p1 = new Person("Alice");
map.put(p1, "Developer");
Person p2 = new Person("Alice");
System.out.println(map.get(p2)); // ✅ Correct: Prints "Developer"
}
}
✅ Why Does This Work?
- Now,
p1.hashCode() == p2.hashCode()
because they have the same name. HashMap
searches the correct bucket and finds the value.
5️⃣ Best Practices for Overriding hashCode()
✔ Always override hashCode()
when overriding equals()
.
✔ Use Objects.hash()
for a simple and reliable implementation.
✔ Include all fields used in equals()
.
✔ Avoid using mutable fields in hashCode()
.
Example: Proper hashCode()
Implementation
@Override
public int hashCode() {
return Objects.hash(name, age, email);
}
This ensures equal objects get the same hash code, avoiding issues in HashSet
and HashMap
.
📌 Summary
Feature | Purpose |
---|---|
hashCode() | Generates an integer for efficient object lookup in HashSet and HashMap . |
Without hashCode() | Hash-based collections may store duplicates or fail lookups. |
Contract | If equals() is overridden, hashCode() must also be overridden. |
Best Practice | Use Objects.hash() to generate reliable hash codes. |
By following these principles, your Java objects will work correctly, efficiently, and predictably in collections! 🚀