🚀 Can Different Objects Have the Same hashCode()
?
Yes! Different objects can have the same hashCode()
, and this is called a hash collision.
The hashCode()
method does not guarantee uniqueness—instead, it tries to distribute objects efficiently in hash-based collections like HashMap
and HashSet
.
1️⃣ Why Can Different Objects Have the Same hashCode()
?
The hashCode()
method returns an integer, but there are far more possible objects than possible hash codes.
- The integer range in Java is 2322^{32}232 (about 4 billion values).
- However, there are an infinite number of possible objects.
- This means multiple objects may produce the same hash code.
Example: Two Different Strings With the Same hashCode()
public class Main {
public static void main(String[] args) {
String s1 = "FB";
String s2 = "Ea";
System.out.println(s1.hashCode()); // 2236
System.out.println(s2.hashCode()); // 2236 (Same as s1!)
}
}
📌 Why does this happen?
- Java’s
String.hashCode()
method follows a specific algorithm that sometimes produces collisions.
2️⃣ What Happens When hashCode()
Collisions Occur?
When two objects have the same hash code, hash-based collections like HashMap
handle them using linked lists or balanced trees.
How HashMap
Handles Collisions:
- Find the Hash Bucket
- Java places objects into buckets based on
hashCode() % arraySize
.
- Java places objects into buckets based on
- Check for a Collision
- If multiple objects have the same hash, they go into the same bucket.
- Use
equals()
to Distinguish Objects- The collection iterates through the bucket and checks
equals()
to find the correct object.
- The collection iterates through the bucket and checks
Example: Two Objects with the Same hashCode()
in a HashMap
import java.util.HashMap;
import java.util.Map;
class Employee {
String name;
public Employee(String name) {
this.name = name;
}
@Override
public int hashCode() {
return 100; // ❌ Intentionally bad hash function (collision guaranteed!)
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Employee employee = (Employee) obj;
return name.equals(employee.name);
}
}
public class Main {
public static void main(String[] args) {
Map<Employee, String> map = new HashMap<>();
Employee e1 = new Employee("Alice");
Employee e2 = new Employee("Bob");
map.put(e1, "Developer");
map.put(e2, "Manager");
System.out.println(map.get(e1)); // Developer
System.out.println(map.get(e2)); // Manager (Even though hashCode() is the same!)
}
}
📌 Why does this work?
hashCode()
puts both objects in the same bucket.equals()
is used to differentiate them.
3️⃣ Is It a Problem If Two Objects Have the Same hashCode()
?
Not really!
Collisions are normal, and Java’s collections handle them efficiently.
However, too many collisions can slow down performance.
🔹 If all objects have the same hashCode()
,
- A
HashMap
becomes a linked list instead of a fast hash table. - Lookups degrade from O(1) to O(n) time complexity.
🚀 How to Minimize Collisions
✔ Use a good hashCode()
function that spreads values evenly.
✔ Include unique fields like id
or UUID
in hashCode()
.
✔ Use Objects.hash()
to generate reliable hash codes.
✅ Correct hashCode()
Example
@Override
public int hashCode() {
return Objects.hash(id, name);
}
📌 Summary
Question | Answer |
---|---|
Can different objects have the same hashCode() ? | ✅ Yes, this is called a hash collision. |
Is hashCode() unique for every object? | ❌ No, multiple objects can have the same hash code. |
What happens when a collision occurs? | The collection stores objects in the same bucket and uses equals() to differentiate them. |
How to avoid too many collisions? | Use a well-distributed hashCode() function that includes unique fields. |
By following these rules, you ensure that hashCode()
works efficiently and correctly in Java collections.