Script Valley
Java: Complete Language Course
Java Collections FrameworkLesson 3.3

Java generics and type-safe collections

generic classes, generic methods, type parameters, bounded type parameters, wildcards, type erasure, raw types, compile-time safety

Generics

Generics make classes and methods work with any type while preserving compile-time type safety. Without generics, you'd use raw Object references and cast everywhere โ€” creating runtime ClassCastException risks.

Generic Class

public class Box {
    private T value;

    public Box(T value) { this.value = value; }
    public T get() { return value; }
    public void set(T value) { this.value = value; }
}
Box strBox = new Box<>("hello");
Box intBox = new Box<>(42);

String s = strBox.get(); // no cast needed
// intBox.set("oops");  // compile error โ€” wrong type

Generic Method

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

System.out.println(max(3, 7));       // 7
System.out.println(max("apple", "mango")); // mango

Wildcards

public double sumList(List list) {
    double total = 0;
    for (Number n : list) total += n.doubleValue();
    return total;
}

? extends Number means any subtype of Number. Use ? super T when you write to a collection. Type erasure removes generic type info at runtime, so List<String> and List<Integer> are both just List in bytecode.

Up next

Java Streams API for collection processing

Sign in to track progress

Java generics and type-safe collections โ€” Java Collections Framework โ€” Java: Complete Language Course โ€” Script Valley โ€” Script Valley