Generic Types

Generics let a class or method work with a type supplied by its user. The type parameter T is replaced conceptually by String, Integer, or another reference type at each use.

A generic Box preserves type information without storing Object and casting later. The compiler rejects putting the wrong kind of value into it.

Keep a box type-safe

class Box<T> {
    private final T value;
    Box(T value) {
        this.value = value;
    }
    T get() {
        return value;
    }
}

public class Main {
    public static void main(String[] args) {
        Box<String> setting = new Box<>("dark");
        Box<Integer> score = new Box<>(91);
        System.out.println(setting.get());
        System.out.println(score.get() + 1);
    }
}

Output:

dark
92

The same Box definition holds a setting string and a wrapped integer while each get has the correct return type.

Use two type parameters

A class can take more than one type parameter. Separate them with a comma, and each one can stand for a different type:

class Labeled<T, L> {
    private final T value;
    private final L label;

    Labeled(T value, L label) {
        this.value = value;
        this.label = label;
    }

    String describe() {
        return label + ": " + value;
    }
}

public class Main {
    public static void main(String[] args) {
        Labeled<Integer, String> lap =
            new Labeled<>(42, "Best lap");
        Labeled<String, Character> seat =
            new Labeled<>("Maya", 'B');
        System.out.println(lap.describe());
        System.out.println(seat.describe());
    }
}

Output:

Best lap: 42
B: Maya

T and L are filled in separately at each use, so lap holds an Integer with a String label and seat holds a String with a Character label.

Avoid raw types such as plain Box. They discard generic checks and can move a type error from compilation to runtime.

Extend the idea by completing a pair that carries two different types.