Why generics
Generics let a class or method work with any type while the compiler still checks types. Errors move from run time (ClassCastException) to compile time, and casts disappear.
List raw = new ArrayList(); // pre-Java 5raw.add("x");Integer n = (Integer) raw.get(0); // compiles, fails at run timeList<String> names = new ArrayList<>();names.add("x");String s = names.get(0); // no cast; adding an Integer won't compile
class Box<T> {private T value;void set(T v) { value = v; }T get() { return value; }}static <T extends Comparable<T>> T max(List<T> list) { // generic method with a boundT best = list.get(0);for (T x : list) if (x.compareTo(best) > 0) best = x;return best;}
Wildcards and PECS
List<Integer> is not a subtype of List<Number> (otherwise you could add a Double to a list of Integers). Wildcards give flexibility instead.
| Wildcard | You can read as | You can add | Use for |
|---|---|---|---|
List<? extends Number> | Number | nothing (except null) | A producer you read from |
List<? super Integer> | Object | Integer | A consumer you write to |
List<?> | Object | nothing | Code that doesn't care about the type |
PECS: Producer Extends, Consumer Super. Collections.copy(List<? super T> dest, List<? extends T> src) is the classic example.
static double sum(List<? extends Number> nums) { // works for List<Integer>, List<Double>…double s = 0;for (Number n : nums) s += n.doubleValue();return s;}static void fill(List<? super Integer> out) { // works for List<Integer>, List<Number>, List<Object>for (int i = 0; i < 3; i++) out.add(i);}
Type erasure
Generic types exist only at compile time. The compiler checks them, inserts casts, and then erases type parameters to their bounds (Object if unbounded). At run time List<String> and List<Integer> are both just List.
- You can't do
new T(),new T[10], orx instanceof List<String>. - You can't overload
f(List<String>)andf(List<Integer>): they erase to the same signature. - Primitives aren't allowed as type arguments: use
List<Integer>, notList<int>. - Static fields can't use the class's type parameter.
Interview questions
Try answering out loud first, then open the model answer.
Q1What is type erasure?intermediate
The compiler uses generic types for checking, then removes them: type parameters become their bound (or Object) and casts are inserted where needed. The bytecode has no generic type information for instances, which keeps compatibility with pre-generics code.
Q2Explain ? extends vs ? super (PECS).intermediate
? extends T means some subtype of T: safe to read as T, but you can't add (you don't know the exact type). ? super T means some supertype of T: safe to add T, but reads only give Object. Producer Extends, Consumer Super.
Q3Why is List<Integer> not a List<Number>?intermediate
If it were, you could pass a List<Integer> where a List<Number> is expected and add a Double to it, breaking the list's type. Generics are invariant; arrays are covariant and fail at run time with ArrayStoreException instead.
Q4Can you create a generic array?advanced
Not directly (new T[n] doesn't compile) because of erasure. Workarounds: use a List<T>, pass a Class<T> and use Array.newInstance, or create an Object[] and cast (with an unchecked warning), as ArrayList does internally.
Q5What is a bounded type parameter?beginner
A type parameter restricted to subtypes of something: <T extends Comparable<T>> lets the method call compareTo on T. Multiple bounds use &: <T extends Number & Comparable<T>>.
Quick check
0 of 3 answered