Sobes.tech
Junior

hashCode() always returns 1 — what's wrong with this? Will HashMap work correctly?

sobes.tech AI

Answer from AI

If the hashCode() method always returns 1, it means that all objects will have the same hash code. As a result, all elements added to a HashMap will go into the same bucket, leading to degraded performance to linear — search, insert, and delete operations will work like in a linked list.

From a correctness standpoint, HashMap will work, but very inefficiently. The main idea of hashing is to evenly distribute objects across buckets to ensure quick access. Returning the same value violates this.

Example:

class BadHash {
    @Override
    public int hashCode() {
        return 1;
    }

    @Override
    public boolean equals(Object obj) {
        return this == obj;
    }
}

// When used in HashMap, all objects will be in one bucket
hashCode() always returns 1 — what's wrong with this… - sobes.tech