Java
Module 17: Java GenericsBeginner24 min read

Generic Classes, Methods, Wildcards & Type Erasure

Achieve compile-time type safety with generics, PECS wildcards (? extends / ? super), and understand JVM type erasure.

Key Takeaways & Core Concepts
  • Upper-Bounded (`? extends T`): Use when the collection produces T values for you to read (List<? extends Number>). You cannot add elements (except null) because the exact subtype is unknown.
  • Lower-Bounded (`? super T`): Use when the collection consumes T values you write into it (List<? super Integer>).
  • Unbounded (`?`): Use when you only need Object methods or List.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.

Generic Repository & PECS Wildcard Sum
1import java.util.List;
2
3class Box<T> {
4 private final T value;
5 Box(T value) { this.value = value; }
6 T get() { return value; }
7}
8
9public class Main {
10 static double sumNumbers(List<? extends Number> nums) {
11 double total = 0;
12 for (Number n : nums) total += n.doubleValue();
13 return total;
14 }
15
16 public static void main(String[] args) {
17 Box<String> label = new Box<>("Java Generics");
18 System.out.println(label.get());
19 System.out.println("Sum: " + sumNumbers(List.of(10, 20.5, 30)));
20 }
21}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
21 lines
Note: `List<? extends Number>` accepts `List<Integer>`, `List<Double>`, or `List<Long>`.

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 T values for you to read (List<? extends Number>). You cannot add elements (except null) because the exact subtype is unknown.
  • Lower-Bounded (`? super T`): Use when the collection consumes T values you write into it (List<? super Integer>).
  • Unbounded (`?`): Use when you only need Object methods or List.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>).

Practice & AssessmentJava Programming Tutorial

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)