Commit 71844de
committed
feat(generic-types): demonstrate pitfalls of using Object-based containers instead of generics
WHAT:
- Added `Box` class that stores a value using a raw `Object` type with getter and setter methods.
- Implemented `BoxType` driver class to showcase runtime type safety issues.
- Example: `box.setValue(1)` followed by `(String) box.getValue()` causes a `ClassCastException`.
WHY:
- Storing values as `Object` allows flexibility but introduces unsafe type casting.
- Manual casting is required whenever retrieving values, leading to potential runtime errors.
- Highlights the need for Java Generics, which enforce compile-time type safety and eliminate unnecessary casts.
HOW:
- `Box` holds an `Object` reference.
- In `BoxType`, inserted an `Integer` into the box, then attempted to cast it into a `String`.
- Program compiles but fails at runtime due to incompatible cast.
BENEFITS (of Generics vs Object-based):
- Generics ensure type consistency at compile time (e.g., `Box<String>` or `Box<Integer>`).
- Eliminates risk of runtime `ClassCastException`.
- Improves code readability and maintainability by avoiding unchecked casts.
REAL-WORLD APPLICATION:
- Demonstrates why pre-generics Java collections (e.g., `Vector`, `Hashtable`) often caused runtime bugs.
- Reinforces importance of parameterized types in modern APIs (e.g., `List<String>` instead of `List`).
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 9c00252 commit 71844de
2 files changed
+6
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
12 | 12 | | |
13 | 13 | | |
14 | 14 | | |
15 | | - | |
16 | 15 | | |
17 | | - | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
18 | 19 | | |
19 | 20 | | |
20 | 21 | | |
21 | 22 | | |
22 | 23 | | |
23 | | - | |
| 24 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
4 | 4 | | |
5 | 5 | | |
6 | 6 | | |
| 7 | + | |
7 | 8 | | |
8 | 9 | | |
9 | 10 | | |
10 | | - | |
| 11 | + | |
0 commit comments