Generics
Generics let a class or method be written once and used with many types, while the compiler still checks that you used the right one. A list of users and a list of orders share the same code but not the same type.
Detailed Explanation
Picture Java before version 5. A List held Object. You put a User in, and when you took it out you got an Object back and had to cast it yourself. That cast was a promise to the compiler that you knew what was in there. When the promise turned out to be wrong, you learned about it as a ClassCastException at runtime, usually far away from the code that put the wrong thing in.
Generics move that promise to compile time. List<User> says the list holds users, the compiler enforces it at every add, and get returns a User with no cast. The error appears while you type instead of during a demo.
The mechanics are small. A type parameter is a placeholder, written in angle brackets, that the caller fills in. class Box<T> introduces T; Box<String> binds it. Methods can have their own parameters too, declared before the return type, as in static <T> T firstOrNull(List<T> items). A bound restricts what can be substituted: <T extends Comparable<T>> means "any type that knows how to compare itself to its own kind", which is what lets a generic max method work at all.
The rule that catches everyone is invariance. List<String> is not a subtype of List<Object>, even though String is a subtype of Object. This looks unhelpful until you see the alternative. Arrays in Java are covariant: Object[] a = new String[1]; compiles, and a[0] = 42; then explodes with ArrayStoreException at runtime. Generics refuse that assignment at compile time instead. When you genuinely need flexibility in one direction, wildcards give it to you explicitly.
Generics in Java are implemented by erasure. The compiler checks your types, then throws most of them away, and the bytecode works with Object plus synthetic casts. This keeps old and new code interoperable, and it is the reason for a family of restrictions: you cannot write new T(), you cannot create a T[], you cannot use instanceof List<String>, and you cannot overload two methods that differ only by type argument.
When do you reach for them? Whenever you write a container, a repository, a cache, a result wrapper, or a callback that should not care which type it carries. Application code usually consumes generics rather than declaring them; library code declares them.
The costs are worth stating plainly. Type parameters cannot be primitives, so List<Integer> boxes every element into a heap object with a header, which is why a million-element List<Integer> uses several times the memory of an int[] and iterates far slower. Deeply nested generic signatures become hard to read, and var since Java 10 exists partly to relieve that. And because of erasure, generics give you no runtime type information at all unless you pass a Class<T> token along yourself.
Code Examples
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
// T is a type parameter: a placeholder the caller fills in at the use site.
class InMemoryRepository<T> {
private final Map<String, T> byId = new HashMap<>();
void save(String id, T entity) {
byId.put(id, entity);
}
Optional<T> findById(String id) {
return Optional.ofNullable(byId.get(id));
}
List<T> findAll() {
return new ArrayList<>(byId.values());
}
}
record User(String id, String email) { }
public class GenericsDemo {
public static void main(String[] args) {
// The diamond on the right could be empty; here we name the argument.
var users = new InMemoryRepository<User>();
users.save("u1", new User("u1", "ana@example.com"));
// No cast anywhere. The compiler knows findById returns Optional<User>.
String email = users.findById("u1").map(User::email).orElse("unknown");
System.out.println(email); // prints: ana@example.com
// users.save("u2", 42); // rejected at compile time, not at runtime
}
}import java.util.List;
class MaxUtil {
// <T extends Comparable<T>> is a bound: T must know how to compare itself.
// Without it, the compiler would not let us call compareTo.
static <T extends Comparable<T>> T max(List<T> items) {
if (items.isEmpty()) {
throw new IllegalArgumentException("max of an empty list");
}
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
public static void main(String[] args) {
// T is inferred from the argument; you never write it at the call site.
System.out.println(max(List.of(3, 17, 8))); // prints: 17
System.out.println(max(List.of("pear", "apple"))); // prints: pear
}
}Common Gotchas
You cannot create a T
`new T()` and `new T[10]` do not compile, because the type is gone by the time the code runs. Pass a `Supplier<T>` for construction, and use `(T[]) new Object[10]` inside a class that never leaks the array, the way `ArrayList` does.
A raw type disables checking everywhere in the expression
assigning to a bare `List` rather than `List<String>` turns off generic checks for every method called on it, including unrelated ones, and gives you back `Object`. Treat the "unchecked" warning as an error in new code.
Generics are invariant on purpose
a method taking `List<Object>` will not accept a `List<String>`. That is not a bug to work around with a cast; it is the compiler stopping you from inserting an `Integer` into a list of strings. Use a wildcard instead.
Boxing is the hidden price
`List<Integer>` stores pointers to heap objects, not machine integers. For numeric hot loops, arrays of primitives or the primitive streams (`IntStream`) avoid that cost entirely.