Advertisement
Beginner Java, Generics

What problem do generics solve compared to using raw types (like a pre-Java-5 List without a type parameter), and how do they improve compile-time type safety?

Short answer

Before generics (Java 5+), collections like List stored elements as plain Object references, meaning retrieving an element required an explicit cast (risking a runtime ClassCastException if the actual stored type didn't match what the code assumed), and nothing prevented…

Save Java mock interview
Advertisement
AModel answer
Before generics (Java 5+), collections like List stored elements as plain Object references, meaning retrieving an element required an explicit cast (risking a runtime ClassCastException if the actual stored type didn't match what the code assumed), and nothing prevented accidentally inserting an incompatible type into the collection in the first place -- generics let you parameterize a class or method with a specific type (List<String>), letting the compiler enforce type correctness at compile time for both insertion and retrieval, catching type mismatches immediately rather than allowing them to surface as a confusing runtime exception potentially far from the actual mistake.
// Pre-generics (raw type): no compile-time type safety
List list = new ArrayList();
list.add("hello");
list.add(42);  // compiles fine, but mixes types!
String s = (String) list.get(1);  // throws ClassCastException at RUNTIME

// With generics: compile-time type safety
List<String> typedList = new ArrayList<>();
typedList.add("hello");
// typedList.add(42);  // COMPILE ERROR, caught immediately
Real-world example
A codebase migration from raw-typed collections to generic List<Customer> immediately surfaces several previously-hidden bugs at compile time where an incompatible object type had been accidentally inserted into a collection, bugs that had previously only manifested as confusing runtime ClassCastExceptions far from their actual root cause.
Likely follow-ups
  • Why does the compiler still allow raw types at all, given generics have been available since Java 5?
  • What specific runtime behavior differs between a raw type and its generic equivalent despite type erasure?
Related topics