Introduced in JDK 5, Generics empower classes, interfaces, and methods to operate on parameterized types. Generics eliminate explicit casting, enforce strict compile-time type checking, and prevent the dreaded ClassCastException.
// Pre-Java 5: Non-generic raw types
List list = new ArrayList();
list.add("Veewom");
list.add(100); // No error at compile time!
// Crashes at runtime with ClassCastException!
String s = (String) list.get(1); // RUNTIME CRASH!
// With Generics: Strict type safety enforced by javac
List<String> list = new ArrayList<>();
list.add("Veewom");
// list.add(100); // COMPILER ERROR! Refuses to compile incompatible types.
String s = list.get(0); // No manual casting required!
public class Box<T> {
private T content;
public void set(T item) { this.content = item; }
public T get() { return this.content; }
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.set("Java 21");
System.out.println("Box contains: " + stringBox.get());
Box<Integer> intBox = new Box<>();
intBox.set(404);
System.out.println("Integer Box: " + intBox.get());
}
}
To restrict type parameters to specific class families, use Bounded Types (e.g. <T extends Number>):
import java.util.List;
public class WildcardDemo {
// Upper Bounded Wildcard (? extends Number): Read-Only (Producer)
public static double sumOfNumbers(List<? extends Number> list) {
double sum = 0.0;
for (Number n : list) {
sum += n.doubleValue();
}
return sum;
}
// Lower Bounded Wildcard (? super Integer): Write-Only (Consumer)
public static void addIntegers(List<? super Integer> list) {
list.add(10);
list.add(20);
}
}
Exam Question: "Can primitive types (like int, double) be used directly as generic type arguments (e.g. List<int>)?"
Answer: No! In Java, generic type parameters must be reference types extending java.lang.Object. Because Type Erasure converts type parameters to Object, primitive types cannot be used. You must use their corresponding Wrapper classes: List<Integer>, List<Double>.
Now let us explore modern functional programming with Lambda Expressions and Method References. Proceed to: Java Lambda Expressions & '::' →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Using generics with collections.
Generic functional interfaces.
Type-safe stream transformations.
Generic optional wrappers.