Skip to content

Commit 67216bb

Browse files
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 changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package HashCode;
2+
3+
public class HashCodeDemo {
4+
public static void main(String[] args) {
5+
String s1 = "ABC";
6+
String s2 = "CBA";
7+
8+
System.out.println("HashCode of " + s1 + " = " + s1.hashCode());
9+
System.out.println("HashCode of " + s2 + " = " + s2.hashCode());
10+
11+
Integer num = 100;
12+
System.out.println("HashCode of Integer 100 = " + num.hashCode());
13+
14+
Double d = 12.34;
15+
System.out.println("HashCode of Double 12.34 = " + d.hashCode());
16+
}
17+
}

0 commit comments

Comments
 (0)