Java.Core.What is the purpose of the hashCode() method?

🚀 Purpose of the hashCode() Method in Java

The hashCode() method returns an integer (hash code) for an object. This hash code is used by hash-based collections like HashMap, HashSet, and HashTable to efficiently store and retrieve objects.


1️⃣ Why Do We Need hashCode()?

In Java, hashCode() is used to:

  1. Optimize Performance in Hash-Based Collections (HashSet, HashMap, HashTable).
  2. Ensure Correct Functionality when overriding equals().
  3. Speed Up Lookups and Inserts by reducing comparisons.

Without hashCode(), Performance Would Be Slow!

If Java only used equals() to compare objects, searching for an element in a HashMap would take O(n) time complexity (linear search).
With hashCode(), it only takes O(1) on average (constant time).


2️⃣ How Does hashCode() Work in Hash-Based Collections?

When an object is used as a key in a HashMap or stored in a HashSet:

  1. Java Calls hashCode() to determine the hash bucket (array index).
  2. If Multiple Objects Have the Same Hash Code (Collision), It Uses equals() to check for equality.
  3. If equals() Returns true, The Object Is Considered the Same; otherwise, it is stored separately.

🔹 Example: Using a HashMap Without Overriding hashCode()

import java.util.HashMap;
import java.util.Map;

class Person {
    String name;

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

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Person person = (Person) obj;
        return name.equals(person.name);
    }
    // ❌ No hashCode() override!
}

public class Main {
    public static void main(String[] args) {
        Map<Person, String> map = new HashMap<>();
        Person p1 = new Person("Alice");
        map.put(p1, "Developer");

        Person p2 = new Person("Alice"); // Different object, but logically equal
        System.out.println(map.get(p2)); // ❌ Expected: "Developer", but prints: null
    }
}

🔴 What Went Wrong?

  • p1.equals(p2) is true (same name).
  • But p1.hashCode() is different from p2.hashCode(), so HashMap searches in the wrong bucket.
  • Lookup fails because hashCode() was not overridden.

3️⃣ What Happens If hashCode() is Not Overridden?

🚨 Violating the equals()hashCode() Contract 🚨

  • If equals() says two objects are equal, they must have the same hash code.
  • If hashCode() is not overridden, HashSet and HashMap may store duplicates or fail lookups.

4️⃣ Correctly Overriding hashCode()

To fix the issue, we must override hashCode() whenever equals() is overridden.

Fixed Version

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

class Person {
    private String name;

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

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

    @Override
    public int hashCode() {
        return Objects.hash(name); // ✅ Includes "name" field in hashCode()
    }
}

public class Main {
    public static void main(String[] args) {
        Map<Person, String> map = new HashMap<>();
        Person p1 = new Person("Alice");
        map.put(p1, "Developer");

        Person p2 = new Person("Alice");
        System.out.println(map.get(p2)); // ✅ Correct: Prints "Developer"
    }
}

Why Does This Work?

  • Now, p1.hashCode() == p2.hashCode() because they have the same name.
  • HashMap searches the correct bucket and finds the value.

5️⃣ Best Practices for Overriding hashCode()

Always override hashCode() when overriding equals().
Use Objects.hash() for a simple and reliable implementation.
Include all fields used in equals().
Avoid using mutable fields in hashCode().

Example: Proper hashCode() Implementation

@Override
public int hashCode() {
    return Objects.hash(name, age, email);
}

This ensures equal objects get the same hash code, avoiding issues in HashSet and HashMap.


📌 Summary

FeaturePurpose
hashCode()Generates an integer for efficient object lookup in HashSet and HashMap.
Without hashCode()Hash-based collections may store duplicates or fail lookups.
ContractIf equals() is overridden, hashCode() must also be overridden.
Best PracticeUse Objects.hash() to generate reliable hash codes.

By following these principles, your Java objects will work correctly, efficiently, and predictably in collections! 🚀

This entry was posted in Без рубрики. Bookmark the permalink.