Using Generic Types
in Java
Master type-safe collections and parameterized types: List<String>, Map<K,V>, and beyond.
What Are Generics?
Generics let you write classes, interfaces, and methods that work with any type while still catching type errors at compile time rather than at runtime. Instead of storing everything as Object and casting, you declare a type parameter like <T>.
Why Generics Matter
The Type Parameter <T>
When you declare Box<T>, the T is a type parameter. When you instantiate Box<String>, the compiler replaces every T with String.
Core Syntax Rules
Common Generic Collections
The Java Collections Framework is fully generic. Each interface accepts type parameters for the elements (or key-value pairs) it stores.
Raw Types vs Generic Types
| Raw Type | Generic Type | |
|---|---|---|
| Declaration | List items | List<String> items |
| Type checking | Runtime only | Compile time |
| Casting needed | Yes, always | No |
| Can mix types | Yes (dangerous) | No (safe) |
| Compiler warnings | "unchecked" warnings | Clean compile |
Step-by-Step: Using Generics
Example 1: List<String>
Example 2: Map<String, Integer>
Example 3: Nested Generics
Writing Your Own Generic Class
You can define multiple type parameters separated by commas. Here, A and B can be any two reference types, even the same type.
Generic Methods
Bounded Type Parameters
Common Mistakes
Summary Reference
| Pattern | Syntax | Example |
|---|---|---|
| Single param | List<E> | List<String> |
| Two params | Map<K, V> | Map<String, Integer> |
| Diamond | new Type<>() | new ArrayList<>() |
| Bounded | <T extends X> | <T extends Comparable<T>> |
| Generic method | <T> ReturnType name(T arg) | <T> List<T> of(T item) |
| Nested | Type<Type<E>> | List<List<Integer>> |
Question 1 of 5
Which declaration correctly creates a List that can only hold String objects?
Question 2 of 5
What is the main advantage of using generic types over raw types?
Question 3 of 5
Given Map<String, List<Integer>> data, what type does data.get("scores") return?
Question 4 of 5
Which line will cause a compile-time error?
Question 5 of 5
What does <T extends Comparable<T>> mean in a method signature?