Sobes.tech
Middle

Will HashMap work if all added keys have the same hashCode()?

sobes.tech AI

Answer from AI

Yes, it will.

With the same hashCode(), all elements will fall into the same "bucket" in HashMap. This will lead to the degeneration of HashMap into a linked list (or a tree if there are enough elements and Java 8+ with TreeNode is used), which significantly worsens the performance of put(), get(), remove() operations to O(n) instead of O(1) on average.

Thus, HashMap will function correctly but will lose its main advantage in speed due to hash collisions. The equals() method is used to distinguish objects with the same hash.

class BadHashKey {
    private String name;

    public BadHashKey(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        return 1; // Always return the same hash code
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        BadHashKey that = (BadHashKey) o;
        return name.equals(that.name); // Check for equality by name
    }

    @Override
    public String toString() {
        return "BadHashKey{" +
               "name='" + name + '\'' +
               '}';
    }
}

// Example usage
// Map<BadHashKey, String> map = new HashMap<>();
// map.put(new BadHashKey("key1"), "value1");
// map.put(new BadHashKey("key2"), "value2"); // Both keys will be in the same bucket
// String value = map.get(new BadHashKey("key1")); // Search will be slow