Skip to content

Generic Classes

The Course
•
20 min study

Generics let a type describe a relationship between values without replacing that relationship with Object and casts. You have used List<String>; now write Box<T>. T is a type parameter chosen by the caller, not a field and not the name of a particular class.

Work through the example

Box stores and returns a value of the same T. new Box<>("Read") lets the compiler infer String from the assignment and argument. new Box<Integer>(25) uses Integer because type arguments must be reference types; Java boxes the int value.

A Box<String> cannot accept an Integer. This catches mistakes before execution. It does not prove the title is meaningful: domain validation is still a separate concern. Keep type checks and business rules distinct. The generic class below rejects null independently of T to make its runtime contract predictable.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        Box<String> title = new Box<>("Read");
        Box<Integer> minutes = new Box<>(25);
        System.out.println(title.get().length());
        System.out.println(minutes.get() + 5);
    }
}

final class Box<T> {
    private final T value;

    Box(T value) {
        if (value == null) {
            throw new IllegalArgumentException("value required");
        }
        this.value = value;
    }

    T get() {
        return value;
    }
}
Check your prediction
Text
4
30

Compare the behavior

Integer.valueOf(25) wraps the primitive int as an Integer object explicitly; assigning an int to an Integer variable would box it automatically.

Using Object loses information. After retrieving an Object, the compiler cannot assume String operations are valid. A cast may compile and still fail at runtime. Generics move this relationship into the type system. Do not use a raw Box without its type argument: that discards the benefit and may introduce unchecked warnings.

Trace the changed case Java
public class Main {
    public static void main(String[] args) {
        Object value = Integer.valueOf(25);
        try {
            String title = (String) value;
            System.out.println(title);
        } catch (ClassCastException expected) {
            System.out.println("Wrong runtime type");
        }
    }
}
Check your prediction
Text
Wrong runtime type

Use a type parameter as a consistent relationship

Replace T mentally with String throughout Box: the field stores String, the constructor accepts String and get returns String. For another instance, T can be Integer without changing the class source. The parameter links these places; it is not a runtime flag deciding which branch to execute.

A raw Box discards that useful relationship. Receiving Object and casting later moves a mistake back toward runtime. Prefer the typed declaration so an incompatible assignment fails before execution. This protects type relationships, not the meaning of data: Box<Integer> can still contain a negative number unless a separate rule rejects it.

Generic storage also does not promise immutable elements. A final T field fixes the reference while a mutable object referenced by T can still change. Reuse the ownership vocabulary from Day 2 instead of assuming that a reusable container is automatically a value object.

Practice independently

Exercise

Generic Classes: practice

Create Pair<A, B> with final fields, a constructor and first()/second() accessors. Store a String title and Integer duration. Print Read: 25 without casts. This exercise allows null values; specify that policy rather than copying Box's validation accidentally.

Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Implement a typed Pair");
    }
}
Hint 1: the idea

Two independent type parameters retain the relationship for each accessor.

Hint 2: a first step

Declare Pair<A, B>, then use A for the first field and B for the second.

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
public class Main {
    public static void main(String[] args) {
        Pair<String, Integer> task = new Pair<>("Read", 25);
        System.out.println(task.first() + ": " + task.second());
    }
}

final class Pair<A, B> {
    private final A first;
    private final B second;

    Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    A first() {
        return first;
    }

    B second() {
        return second;
    }
}

Expected output:

Text
Read: 25

Change it and test again

Try assigning task.second() to a String variable. Read the compiler error, then restore it. Create a Pair<Integer, String> as well. Explain why reversing type arguments changes the accessor types without changing the Pair implementation.

Explain before moving on

Why does Pair<String, Integer> avoid a cast? What does it fail to prove about a negative duration? Tomorrow's reuse should never erase the validation rules you already built.

Was this article helpful?

Your response is saved on this device.