Why were generics introduced in Java?
Must Know🌱 FresherBefore generics (Java 5), collections stored plain Object — you got no compile-time type checking on what you put in, and every read required an explicit, unchecked cast that could fail at runtime with a ClassCastException far away from the actual bug. Generics let you parameterize a class/method with a type, so the compiler enforces type-correctness at compile time and inserts the casts for you automatically and safely.
// Before generics
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0); // manual cast, could fail at runtime for wrong content
// With generics
List<String> list = new ArrayList<>();
list.add("hello");
String s = list.get(0); // compiler already knows it's a String, no cast needed