generics

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

That ran Generics add compile time type checking without creating a new class for every type

Why generics

Before generics, collections held Object Every read needed a cast A wrong cast failed at runtime, not at compile time

Generics move that failure earlier They do not change the runtime types

Wildcards

List<? extends Number> values;

? extends reads from the collection ? super writes into it That is the PECS rule: producer extends, consumer super

Invariance

List<Integer> is not a subtype of List<Number> That surprises people coming from arrays, where Integer[] is a subtype of Number[] The generic version is safer and prevents a store of a wrong type

Erasure

Generics are erased at compile time At runtime, List<String> and List<Integer> are the same raw type That is why you cannot use new T() or instanceof T

Next

Exceptions in 07 exceptions

Posted