Java Tutorial: Generics
Write type-safe reusable code with generics — generic classes, methods, bounded types, wildcards, and the Collections API.
One class, any type
Before generics, Java collections held `Object` — you'd put a `String` in, take an `Object` out, and cast it manually. Casting failed at runtime with cryptic errors.
Generics move those errors to compile time. `List<String>` can only hold Strings — the compiler rejects anything else.
What you'll learn in this Java generics tutorial
This interactive Java tutorial has 5 hands-on exercises. Estimated time: 20 minutes.
- Generic classes — `<T>` is a type parameter — a placeholder replaced when you create the class.
- Generic methods — Methods can be generic independently of their class:
- Bounded type parameters — Restrict `T` to specific types using `extends`:
- Wildcards — ? for flexible methods — Wildcards handle situations where you don't know or don't care about the exact type:
- Build a generic stack — Final challenge — no starter code.
Java Generics concepts covered
- One class, any type