# Generics, Wildcards and Type Erasure

> What are generics and why does Java use type erasure? What are bounded types and wildcards, and what is the PECS rule?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-generics-type-erasure
Last updated: 2026-11-28

Difficulty: Advanced

## Question

What are generics and why does Java use type erasure? What are bounded types and wildcards, and what is the PECS rule?

## Answer

Generics look simple until an interviewer asks about wildcards, and then many candidates go quiet. Let's build the topic from the ground up so nothing feels magical.

Before Java 5, collections stored Object. You would put a String in a List, take it out, cast it, and hope. A wrong cast blew up at runtime with a ClassCastException. Generics move that check to compile time: List<String> says only Strings go in, and the compiler inserts casts for you when reading. They also let you write reusable code such as one sorting method for any comparable type.

To keep compatibility with old code and old JVMs, Java implemented generics with type erasure. During compilation the compiler checks type correctness, and then erases the type parameters: an unbounded T becomes Object, and a bounded T extends Comparable<T> becomes Comparable. Casts are inserted where needed. So at runtime, List<String> and List<Integer> are both just List. Consequences of erasure that interviewers ask about: you cannot write new T(), new T\[10\] or instanceof List<String>; you cannot use primitives as type arguments; you cannot overload two methods that differ only in generic argument types since they have the same erasure; static fields cannot use the class type parameter; and you cannot catch or throw generic types. Generic array creation is disallowed because arrays are reified (they know their element type at runtime) while generics are not, and mixing them would break type safety.

Bounded type parameters restrict what T can be. In <T extends Comparable<T>> the method can call compareTo on T. Multiple bounds use &.

Now wildcards, the part people fear. A common surprise is that List<Integer> is not a subtype of List<Number>, even though Integer is a Number. Generics are invariant. If it were allowed, you could add a Double through a List<Number> reference to what is really a list of Integers. Wildcards give flexibility. List<?> means a list of unknown type: you can read elements as Object but cannot add anything except null. List<? extends Number> is an upper-bounded wildcard: it can be a list of Integer, Double and so on; you can read Numbers safely, but you cannot add (except null), because the compiler does not know the exact element type. List<? super Integer> is lower-bounded: it can be a list of Integer, Number or Object; you can add Integers safely, but reads return only Object.

That leads to PECS: Producer Extends, Consumer Super. If a parameter produces values that you read, use extends. If it consumes values that you write into it, use super. Collections.copy(List<? super T> dest, List<? extends T> src) is the textbook example.

Heap pollution is the last point: with raw types or unchecked casts, you can sneak a wrong type into a generic collection. The compiler warns, and the ClassCastException appears later at the read site, far from the actual bug. So never ignore unchecked warnings casually.

## Code examples

### Bounded methods, erasure and heap pollution

```
import java.util.*;

public class GenericsDemo {
    static <T extends Comparable<T>> T max(T a, T b) {
        return a.compareTo(b) >= 0 ? a : b;
    }

    static double sum(List<? extends Number> nums) {
        double total = 0;
        for (Number n : nums) {
            total += n.doubleValue();
        }
        return total;
    }

    static void fill(List<? super Integer> sink) {
        sink.add(1);
        sink.add(2);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void main(String[] args) {
        System.out.println(max(3, 7));
        System.out.println(max("pear", "apple"));
        System.out.println(sum(List.of(1, 2.5, 3L)));

        List<Object> objs = new ArrayList<>();
        fill(objs);
        System.out.println(objs);

        System.out.println(new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass());

        List<String> strs = new ArrayList<>();
        List raw = strs;
        raw.add(42);
        try {
            String s = strs.get(0);
        } catch (ClassCastException e) {
            System.out.println("CCE at read");
        }
    }
}
```

Extends wildcard is used to read (producer), super wildcard to write (consumer). Erasure makes both ArrayList types the same class at runtime. The raw type lets an Integer slip into a List<String>, and the compiler-inserted cast fails only when the element is read.

## Key points

- Generics give compile-time type safety and remove casts.
- Type erasure removes type arguments at runtime; List<String> and List<Integer> share one class.
- Generics are invariant: List<Integer> is not a List<Number>.
- PECS: use extends to read (producer) and super to write (consumer).
- You cannot create generic arrays or instantiate T with new.

## Common follow-up questions

- Why can't you create a generic array?
- What is a bridge method?
- What is the difference between List<?> and List<Object>?
- What is heap pollution?

## Interview tips

- Lead with the reason erasure exists: backward compatibility. Then list its consequences.
- Use PECS by name and cite Collections.copy as the example.

## Concepts covered

Generics, Type Erasure, Bounded Types, Wildcards, PECS

Previous: [Fail-Fast vs Fail-Safe Iterators](https://www.internhack.in/learn/interview/java-interview/java-fail-fast-vs-fail-safe) · Next: [JVM Memory: Heap, Stack, Metaspace](https://www.internhack.in/learn/interview/java-interview/java-jvm-memory-model) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [Garbage Collection Basics and GC Roots](https://www.internhack.in/learn/interview/java-interview/java-garbage-collection-basics)
- [Thread vs Runnable and the Thread Lifecycle](https://www.internhack.in/learn/interview/java-interview/java-thread-vs-runnable)
- [synchronized vs volatile: Visibility, Atomicity and Ordering](https://www.internhack.in/learn/interview/java-interview/java-synchronized-volatile)
- [wait(), notify() and the Producer-Consumer Pattern](https://www.internhack.in/learn/interview/java-interview/java-wait-notify)
- [Deadlock: Conditions, Detection and Prevention](https://www.internhack.in/learn/interview/java-interview/java-deadlock)
- [ExecutorService, Thread Pools and Future](https://www.internhack.in/learn/interview/java-interview/java-executorservice-thread-pools)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
