Learn · OOP & Java
Generics
Generics let you write code that works with any type while still catching type mistakes before the program even runs. Those <angle brackets> you see everywhere — this is them.
Before we start
- What generics are and the problem they solve
- How List<String> gives you type safety
- Why generics catch bugs at compile time
- Reading angle-bracket types
- Explain why List<String> beats a raw list
- Read and write basic generic types
- Say what type safety buys you
Why you’re learning it: every collection is generic (List<String>), and understanding them makes Java code readable instead of mysterious. ⏱️ ~20 min.
The idea — a labelled box
Imagine a storage box. A plain box could hold anything — but then you never know what you’ll pull out, and you might grab an apple expecting a book. A labelled box — “Apples only” — guarantees what’s inside. List<String> is a box labelled “Strings only”: the compiler won’t let you put a number in, and won’t make you double-check what you take out.
What it saves you
A raw list holds anything. You must cast on the way out, and a wrong type explodes at runtime — the worst time to find out.
List<String> — the compiler catches a wrong type before you run, and no casting needed. Bugs found early are cheap.
Reading them
List<String>— a list of StringsMap<String, Integer>— a map from String keys to Integer values<T>— a placeholder “some type”, filled in when used (how the library authors write reusable code)
Where you’ll use it — real life
You already use generics whenever you type List<Order>.
Type errors caught at compile time never reach production.
Write one method that works for any type, safely.
The type tells the next dev exactly what’s inside.
Out loud: “What problem do generics solve, and why is catching a type error at compile time better than at runtime?” Log it in your Journal.
Back to your Siemens roadmap →