Commit 67216bb
committed
feat(HashCodeDemo): show hashCode() behavior for String, Integer, and Double
What
- Added `HashCodeDemo` class in `HashCode` package.
- Demonstrates the use of `.hashCode()` on:
- `String` (`"ABC"` and `"CBA"`)
- `Integer` (`100`)
- `Double` (`12.34`)
- Prints each value alongside its computed hash code.
Why
- To illustrate how Java computes and uses hash codes across different object types.
- Shows that different objects generally produce different hash codes, but collisions are possible.
- Reinforces the idea that `hashCode()` is consistent with `equals()` contract.
How
- Step 1: Create two strings (`"ABC"`, `"CBA"`) and print their hash codes.
- Step 2: Create an `Integer` with value `100` and print its hash code.
- Step 3: Create a `Double` with value `12.34` and print its hash code.
Logic
- Inputs: fixed literals (`"ABC"`, `"CBA"`, `100`, `12.34`).
- Outputs: console logs of their hash codes.
- Flow:
1. Instantiate or assign values.
2. Call `.hashCode()` on each.
3. Print results.
Real-life applications
- Hash codes are critical for performance in hash-based collections (`HashMap`, `HashSet`, `Hashtable`).
- Used in caching, lookups, and equality checks.
- Helps developers understand how Java’s hashing mechanism works internally.
Notes
- `String.hashCode()` is computed from character values with polynomial accumulation.
- `Integer.hashCode()` simply returns the int value.
- `Double.hashCode()` returns a hash derived from its IEEE 754 bit representation.
- Hash codes are not guaranteed to be unique; collisions can occur.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 16e0699 commit 67216bb
File tree
1 file changed
+17
-0
lines changed- Section 25 Collections Frameworks/Map Interface/HashMap/src/HashCode
1 file changed
+17
-0
lines changedLines changed: 17 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
0 commit comments