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) constyastd::equal_to<T>) dena parta hai. - Java: Aap custom key class ke andar hi
hashCode()aurequals(Object o)methods ko override karte hain.
Core Design Rules for Both Languages
- Equality Consistency:
a.equals(b)true hai toa.hashCode() == b.hashCode()lazmi ho. - 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.
- 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_treturn type:std::unordered_maphash value ke liyestd::size_texpect karta hai.constaurnoexcept:operator()koconstrakhna zaroori hai kyunkeconstmaps 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
31in Java?31aik odd prime number hai;31 * iko JVM(i << 5) - imein optimize kar sakta hai aur bit distribution bhi kaafi clean rehti hai. - Subclasses &
equalssymmetry: Agar class non-final ho, togetClass()vsinstanceofka khayal rakhein taakea.equals(b)aurb.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.
