Skip to content

Commit 35e353e

Browse files
committed
feat(HashCodeAndEqualsMethod): demonstrate importance of overriding equals() and hashCode() in HashMap keys
What - Added `HashCodeAndEqualsMethod` class with a `main` method. - Introduced a custom `Person` class that overrides `equals()` and `hashCode()`. - Demonstrates how `HashMap` uses these methods for key comparison and replacement. - Also included an example with `Map<String, Integer>` to show default behavior. Why - To explain how Java collections like `HashMap` rely on both `hashCode()` and `equals()` to store and retrieve values. - Shows that without proper overrides, logically equal objects may still be treated as different keys. - Reinforces the contract: if two objects are equal (`equals()` returns true), their `hashCode()` must be the same. How 1. Created three `Person` objects: - `p1("Alice", 1)` - `p2("Bob", 2)` - `p3("Alice", 1)` (same values as p1). 2. Inserted all three into a `HashMap<Person, String>`. - `p1 → "Engineer"` - `p2 → "Designer"` - `p3 → "Manager"` 3. Because `p1.equals(p3)` is true and both have same hashCode, `p3` replaces the value of `p1` inside the map. 4. Verified by printing: map size is `2` and `p1`/`p3` return `"Manager"`. 5. Added a `Map<String, Integer>` demo: - `"Shubham"` added twice → second value replaces first. - `"Neha"` added once. Logic - Step 1: Insert keys into map. - Step 2: HashMap computes index using `hashCode()`. - Step 3: If multiple keys fall in same bucket, it checks `equals()`. - Step 4: If equal → replaces value; if not → inserts new entry. - Step 5: Demonstrate with custom objects (`Person`) and built-in type (`String`). Real-life Applications - Correct behavior in caching, sets, and maps where uniqueness of keys is required. - Critical when using objects as keys in `HashMap`, `HashSet`, `Hashtable`. - Avoids subtle bugs where duplicates may incorrectly appear due to missing overrides. Notes - Always override `equals()` and `hashCode()` together. - Use `Objects.hash()` for concise hashCode implementations. - Use `Objects.equals()` for safe null-aware comparisons in `equals()`. - Inconsistent implementation can break contract: two equal objects must always have the same hash code. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 67216bb commit 35e353e

File tree

2 files changed

+126
-13
lines changed

2 files changed

+126
-13
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
Code Recap:
2+
3+
HashMap<Person, String> map = new HashMap<>();
4+
Person p1 = new Person("Alice", 1);
5+
Person p2 = new Person("Bob", 2);
6+
Person p3 = new Person("Alice", 1);
7+
8+
map.put(p1, "Engineer");
9+
map.put(p2, "Designer");
10+
map.put(p3, "Manager");
11+
12+
👉 Yahaan hum ek `HashMap` bana rahe hain jisme **key = Person object** aur **value = Job title (String)**.
13+
- `p1` = Alice, id=1
14+
- `p2` = Bob, id=2
15+
- `p3` = Alice, id=1 (same data as p1, lekin alag object)
16+
17+
---
18+
19+
Step-by-Step Internal Working:
20+
21+
1. **map.put(p1, "Engineer");**
22+
- `p1.hashCode()` calculate hua.
23+
- Maan lo bucket index = 5 aaya.
24+
- `p1` key bucket[5] me insert ho gaya → value "Engineer".
25+
26+
```
27+
Bucket[5] → (p1 -> Engineer)
28+
```
29+
---
30+
31+
2. **map.put(p2, "Designer");**
32+
- `p2.hashCode()` nikala, maan lo index = 9 aaya.
33+
- Key `p2` bucket[9] me store ho gaya → value "Designer".
34+
35+
```
36+
Bucket[5] → (p1 -> Engineer)
37+
Bucket[9] → (p2 -> Designer)
38+
```
39+
40+
---
41+
42+
3. **map.put(p3, "Manager");**
43+
- `p3.hashCode()` nikala.
44+
- Kyunki `p3` bhi `"Alice", 1` hai, iska hashCode same as `p1`.
45+
- Matlab bucket index = 5 aaya (same as p1).
46+
- Ab bucket[5] ke andar `equals()` check hoga:
47+
- `p1.equals(p3)` → true (kyunki name aur id dono same).
48+
- Isliye HashMap ne purani value `"Engineer"` replace karke nayi value `"Manager"` daal di.
49+
50+
```
51+
Bucket[5] → (p3 -> Manager) // replace
52+
Bucket[9] → (p2 -> Designer)
53+
```
54+
---
55+
56+
Output Behavior
57+
58+
System.out.println("HashMap Size: " + map.size());
59+
// Output: 2 (p1 aur p3 same key consider hue)
60+
61+
System.out.println("Value for p1: " + map.get(p1));
62+
// Output: Manager (Engineer replace ho gaya)
63+
64+
System.out.println("Value for p3: " + map.get(p3));
65+
// Output: Manager
66+
67+
---
68+
69+
Dusra Example: Strings as Keys
70+
71+
map1.put("Shubham", 90); // new entry
72+
map1.put("Neha", 92); // new entry
73+
map1.put("Shubham", 99); // same key → replace 90 with 99
74+
```
75+
76+
Resulting Map:
77+
```
78+
"Shubham" → 99
79+
"Neha" → 92
80+
```
81+
82+
---
83+
84+
ASCII Flow Diagram:
85+
86+
Insert p1("Alice",1) → hash=5 → bucket[5] → store (Engineer)
87+
88+
Insert p2("Bob",2) → hash=9 → bucket[9] → store (Designer)
89+
90+
Insert p3("Alice",1) → hash=5 → bucket[5]
91+
|
92+
|--> check equals(p1,p3) = true
93+
|--> replace old value "Engineer"
94+
v
95+
bucket[5] → (p3 -> Manager)
96+
```
97+
98+
99+
Key Takeaways:
100+
101+
1. **HashMap key lookup = hashCode() + equals():**
102+
- Pehle `hashCode()` se bucket milta hai.
103+
- Fir bucket ke andar `equals()` check hota hai.
104+
105+
2. **Duplicate Keys → Replace Value**
106+
- Agar `hashCode()` same hai aur `equals()` true hai → key same maana jaata hai aur value replace hoti hai.
107+
108+
3. **Why override hashCode() and equals()?**
109+
- Custom objects (Person) ko key banane ke liye correct equality define karna zaroori hai.
110+
- Nahi toh HashMap unhe alag objects treat karega, chahe data same ho.
111+
112+
4. **Strings Example**
113+
- `"Shubham"` key dobara daalne pe value overwrite ho jaati hai (90 → 99).
114+
115+
1. HashMap key comparison do steps me hota hai:
116+
• Pehle hashCode() check karke bucket find karo.
117+
• Fir bucket ke andar equals() se compare karo.
118+
119+
2. Agar hashCode() aur equals() dono match ho gaye → key same hai → value replace ho jaati hai.
120+
3. Agar hashCode() same hai but equals() false hai → collision handle hota hai (LinkedList/TreeNode ban ke).
121+
4. Isliye custom objects (Person) ko HashMap key banate time hashCode() aur equals() override karna zaroori hai.

Section25CollectionFramework/src/CustomHashMapDemo/HashCodeAndEqualsMethod.java renamed to Section 25 Collections Frameworks/Map Interface/HashMap/src/HashCodeAndEqualsMethod/HashCodeAndEqualsMethod.java

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package CustomHashMapDemo;
1+
package HashCodeAndEqualsMethod;
22

33
import java.util.HashMap;
44
import java.util.Map;
@@ -25,20 +25,12 @@ public static void main(String[] args) {
2525

2626

2727
Map<String, Integer> map1 = new HashMap<>();
28-
map1.put("Shubham", 90); // hashcode1 --> index1
29-
map1.put("Neha", 92); // hashcode2 --> index2
30-
map1.put("Shubham", 99); // hashcode1 --> index1 --> equals() --> replace
31-
28+
map1.put("Shubham", 90); // hashcode1 --> index1
29+
map1.put("Neha", 92); // hashcode2 --> index2
30+
map1.put("Shubham", 99); // hashcode1 --> index1 --> equals() --> replace
3231
}
3332
}
3433

35-
/*
36-
we are demonstrating how HashMap works internally when we use custom objects (Person) as keys.
37-
38-
Specifically, we are implementing the hashCode() and equals() methods to ensure proper behavior when storing and
39-
retrieving values from a HashMap.
40-
*/
41-
4234
class Person {
4335
private String name;
4436
private int id;
@@ -80,4 +72,4 @@ public boolean equals(Object obj) {
8072
public String toString() {
8173
return "id: " + id + ", name: " + name;
8274
}
83-
}
75+
}

0 commit comments

Comments
 (0)