Skip to content

Commit 2a9ded8

Browse files
committed
Hash Code Basics.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent aa7296c commit 2a9ded8

File tree

1 file changed

+69
-0
lines changed
  • Section 25 Collections Frameworks/Map Interface/HashMap/src/HashCode

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
1. Hash Code Basics:
2+
3+
- Java me har Object class ke paas ek method hota hai → `hashCode()`.
4+
- Ye ek **integer value** generate karta hai jo object ke memory ya content par based hota hai.
5+
- Purpose: is value ka use hashing structures (like HashMap, HashSet) me **bucket index nikalne** ke liye hota hai.
6+
7+
Formula (simplified):
8+
bucketIndex = abs(hashCode) % numberOfBuckets
9+
10+
---
11+
12+
2. Default hashCode():
13+
- Agar aap apna `hashCode()` override nahi karte, to `Object` class ka default method use hota hai jo mostly
14+
object ke memory address se integer generate karta hai.
15+
- Matlab: do alag objects, even with same content, alag hashCodes de sakte hain.
16+
17+
---
18+
19+
3. String hashCode():
20+
- String class me `hashCode()` override kiya gaya hai → woh character sequence par based hota hai.
21+
- Formula (Java source code):
22+
23+
```java
24+
public int hashCode() {
25+
int h = 0;
26+
for (int i = 0; i < value.length; i++) {
27+
h = 31 * h + value[i];
28+
}
29+
return h;
30+
}
31+
```
32+
33+
Example:
34+
`"ABC"` ka hashCode =
35+
h = (65) → 'A'
36+
h = 31*65 + 66 = 2081 → add 'B'
37+
h = 31*2081 + 67 = 64458 → add 'C'
38+
39+
---
40+
41+
4. Wrapper Classes (Integer, Double, etc.):
42+
- Integer ke liye `hashCode()` simple hota hai:
43+
`Integer.hashCode(x) = x`
44+
- Double ke liye: binary representation use karke hash generate hota hai.
45+
- Matlab wrapper classes apne value ko hashCode me convert kar dete hain.
46+
47+
---
48+
49+
5. Custom Classes:
50+
- Agar aap khud ki class ko HashMap ya HashSet me key ke roop me use karna chahte ho,
51+
toh **aapko hashCode() aur equals() override karna zaroori hai**.
52+
- Best practice: dono methods consistent hone chahiye.
53+
- Agar `a.equals(b)` true hai → to `a.hashCode() == b.hashCode()` bhi hona chahiye.
54+
55+
---
56+
57+
6. Why 31 multiplier in String hashCode?
58+
- 31 ek prime number hai → collisions kam hote hain.
59+
- Multiplication with 31 ko compiler efficiently `shift` aur `subtract` karke kar sakta hai (31*h = (h<<5)-h).
60+
- Isse performance bhi acchi hoti hai.
61+
62+
---
63+
64+
7. Recap:
65+
✔ `hashCode()` ek integer fingerprint deta hai.
66+
✔ String ke liye → 31 multiplier + characters.
67+
✔ Integer ke liye → direct value.
68+
✔ Custom classes ke liye → override `equals()` & `hashCode()`.
69+
✔ Ye value Map ke andar bucket index nikalne ke liye use hoti hai.

0 commit comments

Comments
 (0)