Junior — Middle
How does HashMap behave if all objects have the same hashCode, which is a constant?
sobes.tech AI
Answer from AI
If all objects in a HashMap have the same hashCode (for example, a constant), then they will all fall into the same bucket of the internal structure. As a result, the HashMap degrades in performance to a linked list (or a tree if the number of elements in the bucket exceeds a threshold), and insert, search, and delete operations will have a complexity of O(n) instead of the expected O(1).
Example:
class BadHash {
int value;
BadHash(int value) { this.value = value; }
@Override
public int hashCode() { return 42; } // constant hash
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BadHash)) return false;
return this.value == ((BadHash) o).value;
}
}
Map<BadHash, String> map = new HashMap<>();
map.put(new BadHash(1), "one");
map.put(new BadHash(2), "two");
// All elements will be in one bucket, slowing down operations.