Skip to content

Commit 1e83e31

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

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed
Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
package Generics;
2+
13
import java.util.ArrayList;
24

35
public class WhyGenerics {
4-
public static void main(String[] args)
5-
{
6+
public static void main(String[] args) {
67
//ArrayList list =new ArrayList();
78

89
ArrayList<String> list = new ArrayList<>();
@@ -13,16 +14,18 @@ public static void main(String[] args)
1314
String s11 = list.get(1);
1415

1516
System.out.println(s);
17+
System.out.println(s11);
1618

1719
//list.add(123);
1820
//list.add(3.14);
1921

20-
//String str = list.get(0); //Cast karna padega string mai list nahi jata.
22+
//String str = list.get(0);
23+
//Cast karna padega string mai list nahi jata.
2124
//Parent class and child class.
2225

2326
String str = (String) list.get(0);
24-
25-
String integer = (String) list.get(1); //int to string can not cast.
27+
String integer = (String) list.get(1);
28+
//int to string can not cast.
2629
//Issue: Type Safety issue and Manual Casting.(Without generics) No compile time checking.
2730
}
28-
}
31+
}

0 commit comments

Comments
 (0)