Generics Basics

Type parameters and type safety

Interview Relevant: Understanding generic types
5 min read

Generics in Java

Generics enable type safety by allowing classes, interfaces, and methods to operate on parameterized types.

Key Idea: Catch type errors at compile time instead of runtime.

Code Examples

Type safety using generics

java
1
2List<String> names = new ArrayList<>();
3names.add("Alice");
4// names.add(10); // āŒ Compile-time error
5          

Use Cases

  • Type-safe collections
  • Reusable components

Common Mistakes to Avoid

  • Using raw types
  • Ignoring generics warnings