Skip to the page

Collections and generics · mid

Generics, wildcards and type erasure

Generics are invariant, so a List<Integer> is not a List<Number>. Wildcards allow read-only or write-only views. Types are erased at runtime.

The notes

What you must know

  • Generics are invariant: if List<Integer> were a List<Number>, a method could add a Double to a list of Integers.
  • List<? extends Number>: you can read Numbers but not add (except null). A producer.
  • List<? super Integer>: you can add Integers; reads give Object. A consumer. Remember: producer extends, consumer super.
  • Erasure: the compiler checks types, removes them and adds casts. At runtime a List<String> is just a List.
  • So there is no new T(), no instanceof List<String>, and no generic array creation.
  • Raw types and unchecked casts cause heap pollution: a ClassCastException far from the real mistake.
  • Arrays are covariant and checked at runtime: Object[] arr = new String[1]; arr[0] = 1; throws ArrayStoreException.
  • Bounded type parameters: <T extends Comparable<? super T>> T max(List<T> list).

The red pen

Common traps: mistake → fix

  • Mistake: List<Integer> can be passed where List<Number> is expected

    Fix: generics are invariant; use List<? extends Number>.

  • Mistake: Generic types exist at runtime

    Fix: they are erased.

  • Mistake: Arrays and generics behave alike

    Fix: arrays are covariant and checked at runtime.

Easy to hard

Questions interviewers ask, easy to hard

  1. Why can you not pass a List<Integer> to a method that takes List<Number>?
  2. What is the difference between ? extends and ? super?
  3. What is type erasure?
  4. What does ArrayStoreException tell you?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview