Imagine a box that can hold anything โ an apple, a book, or a cat. That's flexible, but messy: how do you know what's inside? You might pull out a cat when you expected an apple.
Generics let you label the box: Box<Apple> only accepts apples. Now the compiler checks it for you. You get flexibility and safety.
A generic class uses a type parameter โ often written as T โ that you fill in when you create an instance. Instead of writing IntBox, StringBox, and DogBox, you write Box<T> once.
Box<Integer> and Box<String> are both valid โ and each is type-checked separately. One blueprint, many types.
A generic method declares its own type parameter, separate from the class. Example: public <T> T firstItem(List<T> items) returns the first item of any list โ with the type preserved.
Call it with firstItem(names), and the compiler infers T = String. You never have to cast. That's the magic of type inference.
Sometimes T can be anything โ but sometimes you want to limit it. A bound says "T must be a Number" or "T must implement the Shape interface."
Example: <T extends Number> means T can be Integer, Double, or Long โ but not String. This lets you safely call number methods inside the class. Bounds are how you stay safe while keeping flexibility.
You already use generics every time you write a typed collection:
List<String> โ a list of strings.
Map<String, Student> โ names mapped to students.
Set<Integer> โ a set of unique numbers.
Try to add a number to a List<String> โ the compiler refuses before your program even runs. That's the compiler being your bodyguard.
Here's a surprise: in Java, generics are checked at compile time but erased at runtime. That means List<String> and List<Integer> look identical inside the running program. This is called type erasure.
Pitfalls to know: you can't create new T(), you can't do instanceof T, and you can't overload on List<String> vs List<Integer>. Generics are powerful โ but not infinite.
| Works โ | Fails โ |
|---|---|
| List<String> names = new ArrayList<>(); | new T() โ no runtime type |
| void add(T item) | obj instanceof T โ erased at runtime |
| <T extends Number> | Primitive types like <int> |
Generics shine brightest in small utilities that many parts of your program reuse. Examples: max(List<T> items), filter(List<T>, Predicate<T>), or a Pair<A, B> class.
Notice the pattern: write the algorithm once, and it works for any type. Write it well and your whole codebase becomes shorter, safer, and easier to maintain.
The labelled box: Write a generic Box<T> class with put(T item) and get(). Use it with an Integer, a String, and a custom Toy class. Then try to mix types and watch the compiler complain.
First item helper: Write a generic method <T> T firstItem(List<T> items). Call it with List<String> and List<Integer>. Notice how the return type is inferred automatically.
Bound test: Write a method <T extends Number> double average(List<T> nums). Test with integers and doubles. Then try it with strings โ the compiler refuses. Explain why.
Typed map: Build a Map<String, Integer> that records the scores of three players. Retrieve a score, then try to insert a string as a score. Watch the type safety kick in.
Pair utility: Write a small Pair<A, B> class with first and second fields. Use it to hold (student name, grade) and (city name, population). One class, many uses.
Erased mystery (bonus): Create List<String> and List<Integer> variables. Try list.getClass() == otherList.getClass() โ and be surprised when they're "equal." That's type erasure in action.
By the end of this module, you'll be able to: write generic classes and methods, use type bounds to constrain types, apply generic collections safely, explain type erasure, and build small type-safe utility classes your whole program can reuse.