Commit 37f4d04
committed
feat: demonstrate type safety with Java Generics vs raw ArrayList usage
WHAT:
- Added `Main.java` to show safe usage of `ArrayList<String>` with Generics.
- Added `Main2.java` to illustrate potential runtime issues when using a raw `ArrayList` without Generics.
HOW:
1. `Main.java`:
- Created an `ArrayList<String>` to store only `String` values.
- Type safety enforced at compile-time; retrieving elements does not require casting.
- Example: `list.get(0)` directly returns a `String`.
2. `Main2.java`:
- Created a raw `ArrayList` (no type parameter).
- Mixed data types inserted: `String`, `Integer`, `Double`.
- Explicit casting required when retrieving elements.
- Demonstrates risk of `ClassCastException` at runtime (e.g., trying to cast an `Integer` to `String`).
WHY:
- Highlights the importance of **Generics** in Java collections.
- Generics provide compile-time type safety and eliminate the need for manual casting.
- Without Generics (raw types), type mismatches are only detected at runtime, leading to potential crashes.
REAL-WORLD APPLICATIONS:
- Generics are widely used in collections (`List<T>`, `Map<K,V>`, `Set<T>`) to ensure data consistency.
- Useful in frameworks (Spring, Hibernate) to enforce strong typing.
- Prevents runtime errors in large codebases by catching type mismatches during compilation.
NOTES:
- `Main2` will throw `ClassCastException` when attempting `String str1 = (String) list.get(1);`
because the second element is actually an `Integer`.
- Best practice: always use parameterized collections with Generics instead of raw types.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 819411e commit 37f4d04
2 files changed
+46
-0
lines changed| 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 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 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 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
0 commit comments