What Happens if hashCode() Always Returns a Constant?
Introduction
In Java, the hashCode() method plays a critical role in hash-based collections like
HashMap, HashSet, and Hashtable. It determines the bucket
where an object will be stored. A well-distributed hash code ensures efficient lookups and inserts.
But what if hashCode() always returns the same constant value? Letβs explore the impact.
Internal Working of HashMap
A HashMap uses the hash code of a key to decide which bucket to place the entry in.
Ideally, keys are spread across multiple buckets, reducing collisions and ensuring average
O(1) performance for put() and get().
Impact of Constant hashCode()
- All entries go into one bucket: Since every key has the same hash code, they all collide into a single bucket.
- Performance degradation: Operations degrade from average
O(1)toO(n)because the map must linearly search through all entries in that bucket. - Excessive collisions: Every insertion causes a collision, requiring equality checks with
equals(). - Treeification in Java 8+: If collisions exceed a threshold, the bucket is converted into a balanced tree, improving worst-case lookup to
O(log n). Still, performance is worse than proper hashing. - Correctness remains intact: The map still works because
equals()ensures correctness, but efficiency is lost.
Example Code
// Example: Constant hashCode impact
import java.util.HashMap;
class BadKey {
private String value;
BadKey(String value) {
this.value = value;
}
@Override
public int hashCode() {
return 1; // constant hash code
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof BadKey)) return false;
return this.value.equals(((BadKey) obj).value);
}
}
public class Main {
public static void main(String[] args) {
HashMap<BadKey, String> map = new HashMap<>();
map.put(new BadKey("A"), "Alpha");
map.put(new BadKey("B"), "Beta");
map.put(new BadKey("C"), "Gamma");
System.out.println(map.get(new BadKey("B"))); // Works but slow
}
}
Interview-Ready Explanation
If asked in an interview, you can say:
βIfhashCode()always returns a constant, all keys collide into the same bucket in aHashMap. This degrades performance from averageO(1)toO(n)for lookups and inserts. In Java 8+, collisions may be treeified toO(log n), but itβs still inefficient. A good hash function should distribute keys evenly across buckets.β
Best Practices
- Always override
hashCode()consistently withequals(). - Ensure hash codes are well-distributed to minimize collisions.
- Use immutable fields that uniquely identify the object to compute hash codes.
Conclusion
Returning a constant from hashCode() does not break correctness, but it destroys
performance. Hash-based collections rely on good hash distribution for efficiency. In interviews,
emphasize both the theoretical impact (performance degradation) and practical consequences
(collisions, treeification). Always design hashCode() methods carefully to ensure
scalability and maintainability in real-world applications.