Generics
Generics Basics
Analyze Java Generics basics, compile-time type safety advantages, parameterized types, and raw types compatibility issues.
Interview: Focuses on type safety validation, runtime ClassCastException prevention, raw types vs parameterized types, and backward compatibility.
Generics were introduced in Java 5 to provide compile-time type safety and eliminate the need for explicit type casting. By parameterizing types, generics allow classes, interfaces, and methods to operate on different types while maintaining compile-time type checks.
Type Safety
Catches type errors early at compile-time instead of letting them fail with a ClassCastException at runtime.
No Explicit Casts
Eliminates verbose casting code. The compiler inserts casts automatically based on type parameters.
Raw Types
Legacy, non-generic forms (e.g. raw List) maintained for backward compatibility. Their use raises compiler warnings.
Why Generics Matter
Before Generics, collections stored raw Object references:
- Developers had to cast elements manually:
String s = (String) list.get(0);. - If an incorrect type was inserted, the cast failed with a
ClassCastExceptionat runtime. - Generics move these checks to compile time, preventing runtime crashes.
Common Pitfalls
- Mixing Raw Types and Generics: Passing generic collections to raw-type legacy methods, which bypasses type checks and can cause heap pollution.
- Expecting runtime type queries: Believing a generic collection holds its type information at runtime, which is prevented by type erasure.
Best Practices
- Avoid Raw Types: Do not use raw types (e.g.
List) in new code. Always specify type parameters (e.g.List<String>). - Prefer diamond syntax: Use the diamond operator
<>during instantiation to let the compiler infer type parameters:List<String> list = new ArrayList<>();.
Interview-Relevant Information
Q1: What are the main benefits of using Generics in Java?
Answer: Generics provide compile-time type safety (preventing type errors at runtime), eliminate the need for manual type casting, and allow developers to implement reusable algorithms that work on different types.
Q2: What are raw types and why are they still allowed?
Answer: Raw types are generic classes or interfaces used without type arguments (e.g. raw List). They are allowed solely for backward compatibility with pre-Java 5 legacy code.
Quick Checklist
Can you state the Java version that introduced generics, explain why raw types raise compiler warnings, and describe the difference between compile-time checks and runtime casts? If yes, you understand generics basics.
Use Cases
Building type-safe data containers and entity collections.
Creating generic data transfer objects (DTOs) in API layers.
Common Mistakes
Using raw types for collections, bypassing compile-time checks.
Relying on manual casts instead of parameterizing type bounds.