Commit 1e83e31
committed
feat(generics): illustrate benefits of generics with ArrayList vs raw types
WHAT:
- Added `WhyGenerics` class to demonstrate type safety provided by generics.
- Compared raw `ArrayList` (pre-Java 5 style) with `ArrayList<String>` using generics.
- Highlighted issues of manual casting and potential runtime `ClassCastException`.
WHY:
- Without generics (`ArrayList list = new ArrayList();`), collections can store any type, but retrieving requires explicit casting.
- This leads to runtime errors if incompatible types are stored (e.g., adding `Integer` and casting to `String`).
- With generics (`ArrayList<String>`), the compiler enforces type safety, eliminating the need for casts.
HOW:
- Created an `ArrayList<String>` and safely added string elements ("Hello", "World").
- Retrieved elements without explicit casts, ensuring compile-time safety.
- Demonstrated commented-out examples of adding integers/doubles, showing compile-time prevention of unsafe operations.
- Added example of forced casting with raw types to show type safety issues.
BENEFITS:
- Generics eliminate the need for repetitive casting.
- Errors are caught at compile time instead of runtime.
- Improves code readability, maintainability, and safety.
REAL-WORLD APPLICATIONS:
- Common in Collections Framework (`List<T>`, `Map<K,V>`, `Set<T>`).
- Used heavily in frameworks like Spring, Hibernate, and Java Streams to ensure type safety.
- Prevents runtime crashes in enterprise-grade applications by leveraging compile-time type checks.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent da2775d commit 1e83e31
1 file changed
+9
-6
lines changedLines changed: 9 additions & 6 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
1 | 3 | | |
2 | 4 | | |
3 | 5 | | |
4 | | - | |
5 | | - | |
| 6 | + | |
6 | 7 | | |
7 | 8 | | |
8 | 9 | | |
| |||
13 | 14 | | |
14 | 15 | | |
15 | 16 | | |
| 17 | + | |
16 | 18 | | |
17 | 19 | | |
18 | 20 | | |
19 | 21 | | |
20 | | - | |
| 22 | + | |
| 23 | + | |
21 | 24 | | |
22 | 25 | | |
23 | 26 | | |
24 | | - | |
25 | | - | |
| 27 | + | |
| 28 | + | |
26 | 29 | | |
27 | 30 | | |
28 | | - | |
| 31 | + | |
0 commit comments