Dung (Donny) Nguyen

Senior Software Engineer

What happens if hashCode() method always returns the same value?

If the hashCode() method always returns the same value for all objects, the performance of hash-based collections like HashMap, HashSet, and Hashtable will be significantly degraded. Here’s what happens:

Impact on Hash-Based Collections

Hash-based collections like HashMap or HashSet use the hash code of an object to decide which “bucket” to place the object in. Ideally, objects with different values should produce different hash codes, spreading the objects evenly across buckets, which makes lookups, insertions, and deletions efficient.

Violation of the Hash Code Contract

While always returning the same value for hashCode() doesn’t violate the contract between equals() and hashCode(), it defeats the purpose of having a hash code in the first place, which is to optimize object lookup and storage.

Example:

Consider the following class with a hashCode() that always returns 1:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Person person = (Person) obj;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return 1; // Same hash code for all objects
    }
}

If we store multiple Person objects in a HashMap or HashSet, all of them will be placed in the same bucket, leading to poor performance as the collection grows.

Summary: