🧪 Generics
12 Java concepts, each explained step by step with real code, a common trap and practice questions.
- Why genericsCompile-time type safety, no casts, no ClassCastException at runtime.
- Generic classes & interfacesclass Box<T>, type parameter naming (T, E, K, V).
- Generic methods<T> T first(List<T> list) and type inference.
- Diamond operatornew ArrayList<>() infers type arguments.
- Bounded type parameters<T extends Number>, multiple bounds with &.
- Generics are invariantList<Integer> is not a List<Number>, unlike arrays.
- Wildcards?, ? extends T (read), ? super T (write).
- PECSProducer Extends, Consumer Super.
- Type erasureGeneric types are erased at runtime; bridge methods.
- Generic restrictionsNo primitives, no new T(), no T[] creation, no instanceof List<String>, no static T fields.
- Raw typesLegacy compatibility, unchecked warnings, heap pollution.
- Recursive bounds<T extends Comparable<? super T>> as used by Collections.max.