Lesson · Generics
Generics basics: the list that remembers its type
18 min readBasics
A list without generics accepts anything and fails later, somewhere else. Generics move that failure to the exact line you typed wrong: the blank <T> is filled in once, and the compiler checks every use.
The list that forgets
Collections used to hold "anything", and the type was remembered by nobody — not by the list, not by the compiler:
List names = new ArrayList(); // no <...>: a list of "anything" names.add("Ada"); names.add(42); // compiles without a word String name = (String) names.get(1); // ClassCastException: 42 is not a String List<String> safe = new ArrayList<>(); // the type lives on the variable safe.add("Ada"); safe.add(42); // error: incompatible types: int cannot be converted to String
Predict: which style fails, and when? The raw list fails at run time — class java.lang.Integer cannot be cast to class java.lang.String — two lines after the mistake. The generic list never compiles: the error points at the add that made it.
A type parameter is a blank
A generic class is written once with a blank — T — that every user fills in:
static class Box<T> { private final T value; // T is whatever the user chooses Box(T value) { this.value = value; } T get() { return value; } // ...and the same T comes back out }
| You write | The compiler reads | In plain words |
|---|---|---|
Box<String> word | a box whose get() returns String | the blank was filled with String |
new Box<>("hello") | new Box<String>("hello") | the diamond copies the type from the left side |
word.get().toUpperCase() | a String method, checked before the program runs | no cast anywhere: the type was never lost |
One class, many boxes. Box<String> and Box<Integer> are the same source file with different answers in the blank — and word.get() already returns a String.
Type filler · one blank, three answers
pick what fills Tclass Box<T> { T get() { return value; } }
Compiles · prints 5
> 5get() hands back a String, and String has length() — the blank solved every check.
The compiler reads every use of the box against the filled blank — before the program gets to run anything.
Methods and interfaces hold blanks too
A blank can belong to a method — the type is then decided at each call — or to a whole interface:
- Generic method:
static <T> T first(List<T> items)— the blank appears in the parameter, so the callfirst(names)fills it in asString. - Generic interface:
interface Store<T>— each implementation picks its type:class StringStore implements Store<String>. - Inference does the filling: you almost never write the type twice —
first(names), notfirst<String>(names).
Where the blank lives decides who fills it. On the class: once, when you create the object. On the method: at every call, from the arguments you pass.
The diamond, and the raw types it replaced
new ArrayList<>() is the diamond: the blank on the right is copied from the left. A generic type used with no <...> at all is called a raw type — it still compiles, but the compiler warns and skips its checks:
List raw = new ArrayList(); // raw type: compiles, with a warning raw.add("hello");
- A plain javac run prints two notes:
uses unchecked or unsafe operationsandRecompile with -Xlint:unchecked for details. - With
-Xlint:uncheckedthe warning names the call:unchecked call to add(E) as a member of the raw type List. - Raw types exist for code written before Java 5; they make the compiler skip its checks and turn mistakes back into runtime cast exceptions.
- A raw type does not mean "any type is fine" — it means "I turned the checker off".
Name what it is: the diamond is the compiler doing the writing for you; a raw type is the compiler doing no checking for you. Same syntax family, opposite outcomes.
What the blank buys you
Four payoffs, every time you fill the blank honestly:
- Fail earlier: the wrong value stops the build at the exact line, not a cast failure three files later.
- No casts:
word.get().toUpperCase()reads directly — the cast still exists, but the compiler writes it for you (that story continues in the type erasure lesson). - Self-documenting APIs:
List<String>andStore<String>say what belongs, without a comment. - One class, many types:
Box<String>andBox<Integer>come from a single source file.
The generics playbook
In order, whenever a type is involved:
- Name the element type the moment you create a collection:
List<String> names = new ArrayList<>(); - Storing or returning one unknown type? Put a blank on the class:
class Box<T>. - Type decided per call? Put a blank on the method:
static <T> T first(List<T> items). - Let the compiler infer: use the diamond, and skip explicit types at call sites.
- Never reach for a raw type to silence an error — fill the blank instead.
The compiler is the front door. Generics move every typing mistake from "a cast exception somewhere later" to "an error at the exact line you typed wrong".
A type parameter is a blank the caller fills in
Box<T> is one class with a blank; Box<String> and Box<Integer> are that same code with different answers. The diamond copies the answer from the left side, inference fills method blanks from the arguments, and the compiler checks every use before the program runs. Raw types opt out of those checks, which is why they warn.
Interview angles
What problem do generics solve?+
They let the compiler check types through collections, containers and APIs: the mistake is caught at the exact line, and casts disappear from the calling code.
Before generics, collections held Object: every get needed a cast, and a wrong element failed at that cast — far from the add that caused it. Generics carry the element type from the declaration through every use, so the check happens while you type.
Common misconception: That generics are only about saving casts — the bigger win is catching mistakes at compile time.
Follow-up: What happens when you try to add an int to a List<String>?
What does `class Box<T>` mean in plain words?+
Box has a blank named T; each user fills it once — Box<String> stores and returns Strings, Box<Integer> stores and returns Integers.
Inside the class, T behaves like a normal type: fields, parameters and return types can all use it. T is not a class and not a supertype of everything — it is a placeholder replaced at each use.
static class Box<T> { private final T value; Box(T value) { this.value = value; } T get() { return value; } }
Common misconception: That T is a real type or that Box<String> and Box<Integer> are different classes.
Follow-up: How does the caller fill the blank in?
When does a blank belong on the method instead of the class?+
When the type is not a property of the object but of one call: static <T> T first(List<T> items) works for any list, and T is filled from the argument at each call.
Class blanks describe what the object holds (once per object). Method blanks describe relationships between parameters and the return type (once per call, inferred from the arguments). A class that holds a String belongs in the class case; a utility that reads any list belongs in the method case.
Common misconception: That the two are interchangeable — a class blank forces every method to share one type, a method blank keeps each call free.
Follow-up: Where did T come from in first(names) — nothing was written in the call.
What is the diamond, and what is a raw type?+
The diamond <> copies the type argument from the left side of the assignment. A raw type is a generic class used with no type argument at all; it compiles with an "unchecked" warning and the checks are skipped.
Raw types exist for backward compatibility with pre-Java-5 code. The compiler keeps them working but warns: unchecked call to add(E) as a member of the raw type List. A raw List is not the same as List<Object> — List<Object> is checked (anything goes, but only Objects), while raw turns the checker off entirely.
Common misconception: That raw types are just old syntax with no consequence — they are the exact place unchecked warnings and heap pollution come from.
Follow-up: Why does the compiler warn instead of refusing to compile?
Why is `String name = (String) names.get(1);` dangerous on a raw list?+
Nothing checked what went in: the add accepted the wrong element silently, and the cast fails at run time, far from the line that made the mistake.
The cast is a promise you make to the compiler; when the promise is based on a raw type, the compiler could not check it. The failure then travels: the add is three lines up, the exception is at the cast, and the fix is at the declaration.
Common misconception: That the cast is where the bug is — the bug is at the add; the cast is only where it surfaces.
Follow-up: What is the one-line fix that makes the mistake impossible?