Lesson 17 of 23

In progress

Course progress

Java

Generics and type safety

Write classes and methods that work for many types, understand type erasure, and use bounded wildcards without fighting the compiler.

Generics let one class or method work with many types while the compiler checks that the types match. The collections library is built on them, and writing your own is easier than the syntax suggests.

What you will learn

  • Declare a generic class and method.
  • Understand erasure and its limits.
  • Use bounded types and wildcards correctly.

A generic class

public class Box<T> {
private T value;
void put(T value) {
this.value = value;
}
T get() {
return value;
}
boolean isEmpty() {
return value == null;
}
}

T is a type parameter, filled in at use:

Box<String> names = new Box<>();
names.put("Ana");
String name = names.get();     // no cast
Box<Integer> counts = new Box<>();
counts.put(3);

Before generics, Box would hold Object, and every get needed a cast that could fail at runtime. Now a mismatch is a compile error: names.put(3) does not compile.

Convention names the parameters T for type, E for element, K and V for key and value, R for result.

Generic methods

static <T> java.util.List<T> repeat(T value, int times) {
java.util.List<T> result = new java.util.ArrayList<>();
for (int i = 0; i < times; i++) {
result.add(value);
}
return result;
}
java.util.List<String> xs = repeat("hi", 3);
java.util.List<Integer> ns = repeat(7, 2);

The type parameter appears before the return type. The compiler infers T from the argument, so the call site stays clean.

Bounded types

static <T extends Comparable<T>> T max(java.util.List<T> values) {
T best = values.get(0);
for (T value : values) {
if (value.compareTo(best) > 0) {
best = value;
}
}
return best;
}

T extends Comparable<T> restricts the type to things that can be compared, which is what makes compareTo available. Without the bound, the method would not compile, because T could be anything.

A bound can be a class, an interface, or both: <T extends Number & Comparable<T>>. The class comes first.

Erasure

Generic type information is erased at runtime. List<String> and List<Integer> are both List in the compiled class, which has consequences:

  • You cannot do new T() or new T[]; the type is unknown at runtime.
  • You cannot use instanceof List<String>; only instanceof List.
  • Overloads that differ only in type arguments clash: f(List<String>) and f(List<Integer>) have the same erasure.

The compiler inserts casts where needed, which is why generic code is safe without runtime overhead. A type parameter also cannot be a primitive, so Box<int> is illegal and Box<Integer> is the closest available, at the cost of an allocation per value.

Wildcards

static long sum(java.util.List<? extends Number> values) { ... }

? extends Number accepts a list of Integer, Double or any subtype, and the method can read numbers but not add to the list, because the exact element type is unknown.

? super Integer accepts a list of Integer, Number or Object, and allows adding an Integer, because any such list can hold one.

The rule of thumb, from the collections library’s own documentation: use extends when you only read, super when you only write, and an exact type when you do both. PECS — producer extends, consumer super.

static void copy(java.util.List<? extends Number> from, java.util.List<? super Number> to) {
for (Number n : from) {
to.add(n);
}
}

Generics and arrays

// List<String>[] lists = new List<String>[10];   // illegal
java.util.List<java.util.List<String>> lists = new java.util.ArrayList<>();

Arrays are covariant and checked at runtime; generics are invariant and checked at compile time. Mixing them is unsafe, so Java forbids generic array creation. Use a list of lists instead.

Variance in practice

java.util.List<Integer> ints = java.util.List.of(1, 2, 3);
java.util.List<? extends Number> nums = ints;   // fine
// java.util.List<Number> bad = ints;           // compile error

List<Integer> is not a List<Number>, even though Integer is a Number, because a List<Number> promises you can add a Double. The wildcard form is how you accept a family of lists for reading.

When not to use generics

If a class is used with exactly one type, a concrete class is simpler. If the type only appears in one method, a generic method may be overkill. Generics pay off when the same structure is genuinely reused across types, which is why the collections library uses them everywhere and application code uses them occasionally.

Trying to create a generic array with new T[n], which does not compile. Pass a Class<T> or an IntFunction<T[]> to allocate, or use a List.

Write a generic Pair<A, B> with accessors first() and second(), then a static method swap that returns a Pair<B, A>.

Show solution
public record Pair<A, B>(A first, B second) { static <A, B> Pair<B, A> swap(Pair<A, B> pair) { return new Pair<>(pair.second(), pair.first()); } public static void main(String[] args) { Pair<String, Integer> p = new Pair<>("age", 42); Pair<Integer, String> q = Pair.swap(p); System.out.println(q.first() + " " + q.second()); } }

The record handles the fields, constructor and accessors. swap declares both type parameters so the return type flips, and inference works from the argument alone. A record cannot be extended, which is fine for a value.

Recap

  • Generics move type errors to compile time and remove casts.
  • Erasure means no new T(), no generic arrays, and no runtime type checks on parameters.
  • Use extends for reading, super for writing, and a bound to call methods on T.

Next, files: reading and writing text without leaking handles.

Why can't I use primitives as type arguments?
Generics work with reference types because erasure makes them `Object`. Wrappers and autoboxing cover the common cases.
What is a raw type?
A generic class used without type arguments, such as `List`. It compiles with warnings and loses type checking; avoid it.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.