Skip to content

Commit 71844de

Browse files
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

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

Section24JavaGenerics/src/GenericTypes/Box.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,13 @@ public void setValue(Object value) {
1212
}
1313
}
1414

15-
1615
/*
17-
Generic types allow you to define a class, interface, or method with placeholders (type parameters) for the data types they will work with.
16+
Generic types allow you to define a class, interface, or method with placeholders (type parameters) for the data
17+
types they will work with.
18+
1819
This enables code reusability and type safety, as it allows you to create classes, interfaces, or
1920
methods that can operate on various types without needing to rewrite the code for each type.
2021
2122
A generic type is a class or interface that is parameterized over types.
2223
For example, a generic class can work with any type specified by the user, and that type can be enforced at compile time.
23-
*/
24+
*/

Section24JavaGenerics/src/GenericTypes/BoxType.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ public class BoxType {
44
public static void main(String[] args) {
55
Box box = new Box();
66
box.setValue(1);
7+
78
String i = (String) box.getValue(); // EXCEPTION !!!
89
System.out.println(i);
910
}
10-
}
11+
}

0 commit comments

Comments
 (0)