Can Two Unequal Objects Have the Same HashCode in Java?
Yes — two objects that are not equal can still have the same hashCode()
value. This scenario is known as a hash code collision, and it's a fundamental aspect of how hashing works.
Why Can This Happen?
Java's hashCode()
method returns a 32-bit integer. Given the limited range of possible hash codes (about 4 billion), and the potentially infinite number of different objects, collisions are inevitable — it's a classic case of the pigeonhole principle.
For example:
java
String a = "FB";
String b = "Ea";
System.out.println(a.hashCode()); // 2236
System.out.println(b.hashCode()); // 2236
System.out.println(a.equals(b)); // false
Despite being unequal, "FB"
and "Ea"
have the same hash code.
The hashCode() and equals() Contract
Java requires that:
- If two objects are equal (
equals()
returns true
), then their hash codes must also be equal. - However, if two objects are not equal, their hash codes can still be the same (though ideally they shouldn’t).
This means:
ObjectshashCode()equals()SameSametrueDifferentSamefalseDifferentDifferentfalse
Why This Matters in Hash-Based Collections
Collections like HashMap
, HashSet
, and Hashtable
use hashCode()
to quickly locate a bucket, and then use equals()
to find the exact match within that bucket.
If multiple objects land in the same bucket (collision), performance can degrade to linear search time. That’s why a good hash function should minimize collisions while satisfying the equals()
/hashCode()
contract.
Best Practices
- Always override
hashCode()
whenever you override equals()
. - Use helper utilities like
Objects.hash()
to build consistent and well-distributed hash codes. - Test your class’s behavior in a
HashSet
or HashMap
to ensure correct equality semantics.
Conclusion
While hash code collisions are normal and expected in Java, equal objects must always produce the same hash code. Understanding this distinction is crucial for writing reliable Java code, especially when working with hash-based collections.