Generic Classes, Methods, Wildcards & Type Erasure
Achieve compile-time type safety with generics, PECS wildcards (? extends / ? super), and understand JVM type erasure.
- Upper-Bounded (`? extends T`): Use when the collection produces
Tvalues for you to read (List<? extends Number>). You cannot add elements (exceptnull) because the exact subtype is unknown. - Lower-Bounded (`? super T`): Use when the collection consumes
Tvalues you write into it (List<? super Integer>). - Unbounded (`?`): Use when you only need
Objectmethods orList.size().
Why Generics (Java 5+)?
Before Java 5, List held raw Object references—meaning you could accidentally insert an Integer into a list of Strings and only discover the bug at runtime via a ClassCastException. Generics shift type checking to compile time and eliminate manual casts.
Invariance & Bounded Wildcards (PECS)
Generic types are invariant: List<Integer> is NOT a subtype of List<Number> (otherwise you could add a Double into an Integer list!). To write flexible APIs, use bounded wildcards following PECS (Producer Extends, Consumer Super):
- Upper-Bounded (`? extends T`): Use when the collection produces
Tvalues for you to read (List<? extends Number>). You cannot add elements (exceptnull) because the exact subtype is unknown. - Lower-Bounded (`? super T`): Use when the collection consumes
Tvalues you write into it (List<? super Integer>). - Unbounded (`?`): Use when you only need
Objectmethods orList.size().
Type Erasure & Restrictions
To preserve backward compatibility with pre-Java 5 bytecode, javac performs Type Erasure: it replaces <T> with its bound (or Object) and inserts synthetic casts. As a result, at runtime List<String> and List<Integer> have the exact same class (ArrayList), and you cannot write new T() or if (obj instanceof List<String>).
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)