Generics Fundamentals & Type-Safe Containers (<T>)
1Concept
Generics provide compile-time type safety, allowing classes, interfaces, and methods to operate on parameterized types. They eliminate the need for manual type casting and prevent `ClassCastException` at runtime.
2Architecture Diagram
Raw Type: List list = new ArrayList(); list.add("text"); (Integer) list.get(0); ---> ClassCastException at runtime!
Generic: List<String> list = new ...; list.add(10); ---> Compile Error caught immediately!3Code Example
Core Java
public class GenericsDemo {
static class Box<T> {
private T content;
public void set(T content) { this.content = content; }
public T get() { return content; }
}
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.set("Type Safe Architecture");
String value = stringBox.get(); // Zero casting required!
Box<Integer> intBox = new Box<>();
intBox.set(2026);
int year = intBox.get();
System.out.println("StringBox: " + value);
System.out.println("IntBox: " + year);
}
}4Expected Output
StringBox: Type Safe Architecture IntBox: 2026
5Key Takeaways
- ✓Type arguments must be reference types (`Integer`, `Double`), not primitives (`int`, `double`).
- ✓Generics provide compile-time safety and self-documenting code APIs.
- ✓Diamond operator `<>` allows compiler type argument inference.