Skip to content
AgileLogics
5 min read

Generics

Prerequisites: Custom exceptions

A generic class or method is written once but works with any type, substituted in via a type parameter (conventionally a single capital letter like T).

class Box<T> {
    private T value;

    void set(T value) {
        this.value = value;
    }

    T get() {
        return value;
    }
}

Box<String> stringBox = new Box<>();
stringBox.set("Hello");
String value = stringBox.get(); // no cast needed — already a String

Box<Integer> intBox = new Box<>();
intBox.set(42);

You've already used generics without necessarily calling them that — List<String> and Map<String, Integer> are both generic types from the standard library.

Common mistakes

  • Trying new Box<int>() — a generic type parameter must be an object type, so primitives use their wrapper class instead (Integer, not int).

Practice

Write a generic method <T> T firstOf(List<T> list) that returns the first element of any list.

Show solution
static <T> T firstOf(List<T> list) {
    return list.get(0);
}