How do you design a custom hash function for custom objects in C++ unordered_map and Java HashMap? | A1LabDavid to DSAEnglish • 18 hours ago

How do you design a custom hash function for custom objects in C++ unordered_map and Java HashMap?

message-square
0
1
How do you design a custom hash function for custom objects in C++ unordered_map and Java HashMap?
How do you design a custom hash function for custom objects in C++ unordered_map and Java HashMap? | A1LabDavid to DSAEnglish • 18 hours ago

Custom Hash Functions: C++ std::unordered_map vs. Java HashMap

Jab kisi custom class ya struct ko hash table ki key banana ho, to hash function aur equality comparison dono ka synchronized hona zaroori hai. Agar do objects equal hain (a == b ya a.equals(b)), to un ka hash code hamesha same hona chahiye (hash(a) == hash(b)). Ulta zaroori nahi hai—alag objects ka hash same aa sakta hai (collision), jo bucket chain ya open addressing se handle hota hai.

C++ (std::unordered_map) aur Java (HashMap) mein is ka mechanism thora mukhtalif hai:

  • C++: Aap ko explicit hash functor/struct (std::size_t operator()(const T& key) const) aur equality operator (bool operator==(const T& other) const ya std::equal_to<T>) dena parta hai.
  • Java: Aap custom key class ke andar hi hashCode() aur equals(Object o) methods ko override karte hain.

Core Design Rules for Both Languages

  1. Equality Consistency: a.equals(b) true hai to a.hashCode() == b.hashCode() lazmi ho.
  2. Immutability of Keys: Key ke woh fields jo hash aur equality mein use ho rahe hain, map mein insert karne ke baad change na hon. Agar key ka hash badal gaya to lookup/delete broken ho jayega.
  3. Good Field Mixing: Sab fields ko simple XOR (^) karne ke bajaye prime multipliers ya bit-mixing (hash << 6, hash >> 2, 31 * h + ...) use karein taake (1, 2) aur (2, 1) jaisi ordered pairs alag hashes dein.

C++ std::unordered_map Design

Maanein hamare paas aik Point2D struct hai jisme int x, y hain:

#include <cstddef>
#include <functional>
#include <unordered_map>

struct Point2D {
    int x;
    int y;

    bool operator==(const Point2D& other) const noexcept {
        return x == other.x && y == other.y;
    }
};

struct Point2DHash {
    std::size_t operator()(const Point2D& p) const noexcept {
        std::size_t h1 = std::hash<int>{}(p.x);
        std::size_t h2 = std::hash<int>{}(p.y);
        // Boost-style hash combination to reduce ordered-pair collisions
        return h1 ^ (h2 + 0x9e3779b97f4a7c15ULL + (h1 << 6) + (h1 >> 2));
    }
};

// Usage:
// std::unordered_map<Point2D, int, Point2DHash> grid_scores;
  • std::size_t return type: std::unordered_map hash value ke liye std::size_t expect karta hai.
  • const aur noexcept: operator() ko const rakhna zaroori hai kyunke const maps bhi hash functor call karte hain.

Java HashMap Design

Java mein Object.hashCode() aur Object.equals(Object) ko override karte hain. Modern Java (Java 7+) mein Objects.hash(...) aasaan hai, lekin hot loops mein autoboxing bachane ke liye manual prime multiplication (31) behtar rehti hai:

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

public final class Point2D {
    private final int x;
    private final int y;

    public Point2D(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point2D other)) return false;
        return x == other.x && y == other.y;
    }

    @Override
    public int hashCode() {
        int result = Integer.hashCode(x);
        result = 31 * result + Integer.hashCode(y);
        return result;
    }
}

// Usage:
// Map<Point2D, Integer> gridScores = new HashMap<>();
  • Why 31 in Java? 31 aik odd prime number hai; 31 * i ko JVM (i << 5) - i mein optimize kar sakta hai aur bit distribution bhi kaafi clean rehti hai.
  • Subclasses & equals symmetry: Agar class non-final ho, to getClass() vs instanceof ka khayal rakhein taake a.equals(b) aur b.equals(a) symmetric rahein.

Complexity

  • Hash Computation: $O(k)$ jahan $k$ key ke fields/elements ki tadaad hai ($O(1)$ for fixed-size primitive fields).
  • Lookup / Insert / Erase: $O(1)$ average time, $O(n)$ worst-case if many keys collide into the same bucket.