Senior
What happens if hashCode() always returns 0? All elements go into one bucket, HashMap expands — will this help?
sobes.tech AI
Answer from AI
If the hashCode() method always returns 0, then all objects will fall into the same bucket in a HashMap. This causes the data structure to degrade to a linked list within that bucket.
As a result, search, insert, and delete operations are no longer close to O(1) and become O(n), where n is the number of elements in the map.
Expanding the HashMap (increasing the number of buckets) in this situation won't help, as all elements will still fall into the same bucket due to the identical hash code. Thus, performance will deteriorate as the number of elements grows.
Example:
class BadHash {
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
}
// Usage
Map<BadHash, String> map = new HashMap<>();
map.put(new BadHash(), "value1");
map.put(new BadHash(), "value2");
// All elements are in one bucket, search is slow