Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 09 / Topic 1 of 10

Why generics exist

Stage 1 Part 4 taught you to write ArrayList<String> and HashMap<String, Integer> as "copy the diamond brackets, don't ask why yet." This section finally answers that question.

Before Java 5, a collection could only hold Object. Anything you took out had to be cast back to its real type by hand, and the compiler could not stop you from putting the wrong thing in.

Real-world example: a courier company's old box class, written before generics existed.

class ObjectBox {
    private Object value;
    void set(Object value) { this.value = value; }
    Object get() { return value; }
}

ObjectBox cityBox = new ObjectBox();
cityBox.set("Pune");
String city = (String) cityBox.get();      // you must remember to cast

ObjectBox mixedUp = new ObjectBox();
mixedUp.set(1760);                          // nothing stops an int going in here
String wrongCast = (String) mixedUp.get();  // compiles fine...
// ...and fails only when it RUNS:
// ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String

The bug sits quietly until the exact line that does the bad cast runs, which can be far away from where the wrong value was put in. A generic class fixes this by taking a type parameter — a placeholder type, written in angle brackets — so the compiler knows, at every line, exactly what type is inside the box.

class Box<T> {              // T is a type parameter, chosen by whoever creates the Box
    private T value;
    void set(T value) { this.value = value; }
    T get() { return value; }
}

Box<String> nameBox = new Box<>();
nameBox.set("Asha Kulkarni");
String name = nameBox.get();   // no cast needed: the compiler already knows T is String
// nameBox.set(1760);          // would NOT COMPILE: int is not a String

T is just a name, like a parameter name in a method; E, K, V, R are common conventions (Element, Key, Value, Result), but any name works. The compiler checks every use of nameBox against String, so the mistake from ObjectBox cannot happen any more — it is caught while you type, not months later in production.

Full program: examples/GenericBox.java.

Done here? The practice set for Part 9 — including the solutions — is on the part page.

Search the guide