Skip to content
javahacks.dev
Java Core

Java Generics Explained From Type Parameters to Wildcards

Java generics explained: type parameters, generic methods, bounds, type erasure, invariance and wildcards, with examples and the limits erasure imposes.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the OpenJDK, Apache Maven, JUnit5, Spring and Gradle logos.

Generics, added in Java 5, give collections and APIs compile time type safety without casts. The design has constraints that follow from how it was implemented.

Type parameters

java
public class Box<T> {
    private T value;
    public void set(T value) { this.value = value; }
    public T get() { return value; }
}

Box<String> b = new Box<>();
b.set("hi");
String s = b.get();       // no cast
b.set(42);                // compile error

T is a placeholder. The diamond <> lets the compiler infer the argument from the left side.

Generic methods

java
static <T> T firstOrDefault(List<T> list, T fallback) {
    return list.isEmpty() ? fallback : list.get(0);
}

String s = firstOrDefault(List.of("a"), "none");

The <T> before the return type declares the method's own parameter, inferred from the arguments.

Bounds

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

T extends Comparable<T> limits the type to those that can compare themselves, so compareTo is available. Multiple bounds use &: T extends Number & Comparable<T>.

Invariance

java
List<String> strings = new ArrayList<>();
List<Object> objects = strings;     // compile error

If this compiled, you could add an Integer through objects and corrupt strings. Arrays are covariant and checked at run time, generics are invariant and checked at compile time. Wildcards give flexibility safely.

Wildcards

java
double sum(List<? extends Number> nums) {      // read only producer
    double s = 0;
    for (Number n : nums) s += n.doubleValue();
    return s;
}

void fill(List<? super Integer> sink) {        // write only consumer
    sink.add(1);
}

? extends T accepts T or subtypes and is for reading. ? super T accepts T or supertypes and is for writing. The rule that decides is covered in PECS. Unbounded ? means "any type" and is used when the type does not matter.

Type erasure

At run time List<String> and List<Integer> are both List. The compiler inserts casts and checks. Consequences:

java
new T();                         // error: no instance creation
T[] arr = new T[10];             // error: no generic array creation
obj instanceof List<String>;     // error: use List<?>
static T field;                  // error: a static field cannot use the class's T

Workarounds: pass a Class<T> token, a Supplier<T> or an IntFunction<T[]>. Erasure also creates synthetic methods, see bridge methods, and can lead to heap pollution.

Practical advice

  • Prefer List<String> over raw List; raw types skip checks and cause ClassCastException.
  • Use bounded wildcards in method parameters to make APIs flexible.
  • Return concrete generic types, not wildcards.
  • Prefer lists to arrays of generics.

A worked example: a generic cache

Tying the pieces together, a small typed cache needs a type parameter on the class, a bound on a method and no casts at the call site:

java
public class Cache<K, V> {
    private final Map<K, V> map = new HashMap<>();

    public V get(K key, Function<? super K, ? extends V> loader) {
        return map.computeIfAbsent(key, loader);
    }
}

Cache<Long, String> names = new Cache<>();
String n = names.get(7L, id -> "user-" + id);

The Function<? super K, ? extends V> parameter accepts a loader that takes a supertype of the key or returning a subtype of the value, which is exactly the flexibility the rules above allow. See also the overload behaviour in overloading versus overriding.

The rule for wildcards, in one line

Producer extends, consumer super. If a method only reads values of type T from a collection, accept Collection<? extends T>, and if it only writes values of type T into one, accept Collection<? super T>. A method that copies from a list of integers into a list of numbers is copy(List<? extends T> src, List<? super T> dst), and it works for Integer into Number and Object, which an invariant List<T> signature would refuse. When you need to both read and write, use a plain type parameter, because the wildcard cannot express it.

Bounded types and what they unlock

A bound makes the methods of the bound available inside the generic code. <T extends Comparable<T>> lets you call compareTo on a T, and <T extends Number> gives you doubleValue(). A recursive bound such as <T extends Comparable<? super T>> is the form the JDK uses for Collections.sort, and the ? super lets a class inherit its ordering from a parent: a java.sql.Timestamp sorts with the compareTo it inherits from Date. If you find a signature with a recursive bound too hard to read, it is acceptable to write the simpler one for internal code.

What erasure forbids

At run time List<String> and List<Integer> are both List, and the compiler removes the type arguments. That is the reason for four restrictions: you cannot write new T(), new T[10] or instanceof List<String>, and you cannot overload two methods that differ only in a generic argument, since both erase to the same signature. A common workaround for creation is to pass a Class<T> token or a Supplier<T>, and for arrays to use Array.newInstance or a List. Knowing the four makes most of the confusing compile errors predictable.

Heap pollution and varargs

A generic varargs parameter, List<String>..., creates an array of a non-reifiable type, and the compiler warns about possible heap pollution. Annotate a method with @SafeVarargs only when it does not store anything into the array and does not expose it, as List.of and Arrays.asList do, and the annotation works only on static, final and private methods and on constructors. An unchecked warning is a place where the compiler stopped checking, and each deserves a comment about why it is safe, or a redesign.

Reading a type from a generic class at run time

Erasure also hides the type argument from reflection on an instance, but not from reflection on a class declaration. A subclass such as class StringList extends ArrayList<String> keeps its parent's type argument in the class file, and getGenericSuperclass() returns it. That trick is behind Jackson's TypeReference and Guava's TypeToken: an anonymous subclass new TypeReference<List<Order>>() {} captures the type for you. Use it when deserializing a generic type, since List.class loses the element type and Jackson returns maps instead of orders.

Common compile errors and what they mean

incompatible types: List<Integer> cannot be converted to List<Number> is invariance, and the fix is a wildcard or a copy. generic array creation is erasure, and the fix is a list. unchecked cast is the compiler telling you that it cannot verify the cast, so isolate it in one small method with a comment. incompatible bounds usually means that the arguments you passed lead to two different inferences for one type variable, and an explicit type witness, Util.<String>merge(a, b), or a local variable with a declared type clears it.

Practical advice

Use generics to remove casts and to state constraints, and stop there. A signature with three type parameters and two wildcards is a sign to introduce a named type for part of it. Prefer simple, readable bounds in public APIs, and expect the callers to be less expert than you. Read the Javadoc of Collections and Stream as a style guide, since they show the idioms you will reuse for years.

When this does not apply

Simple code that uses collections rarely needs to define generics. Writing them matters for libraries and utility code. Reference: the Java generics tutorial and JLS chapter 4.5.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.