# Generics In Depth — Advanced Java

Source: https://www.geekswithgeeks.com/en/advanced-java/adv-generics

> Go deep on Java generics — type erasure and its consequences, bounded type parameters, wildcards, and the producer-extends / consumer-super (PECS) rule.

## Type erasure

Generics are a **compile-time** feature. After type checking, the compiler erases type parameters to their bounds (usually `Object`), so `List<String>` and `List<Integer>` share one runtime class. Consequences: no `new T[]`, no `instanceof List<String>`, and overloads can't differ only by generic type.

## Bounded type parameters

`<T extends Comparable<T>>` restricts `T` so you can call `compareTo`. Bounds let a generic method use the capabilities it needs while staying reusable.

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

## PECS

**Producer Extends, Consumer Super.** Use `? extends T` for a source you only read from, `? super T` for a sink you only write to. `Collections.copy(List<? super T> dest, List<? extends T> src)` is the canonical example.
