Java

Generic Class with Type Parameter

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Stamp out type-safe containers and helpers — same class body, multiple element types. The `<T>` declaration is what makes it generic.
Java
Raw
public class Box<T> {
    private T value;

    public Box(T value) { this.value = value; }
    public T get()                { return value; }
    public void set(T value)      { this.value = value; }

    public <U> Box<U> map(java.util.function.Function<T, U> f) {
        return new Box<>(f.apply(value));
    }
}

void demo() {
    Box<String> sb = new Box<>("hello");
    System.out.println(sb.get());                    // hello

    Box<Integer> ib = sb.map(String::length);
    System.out.println(ib.get());                    // 5

    // Diamond operator — let the compiler infer
    Box<java.util.List<String>> lb = new Box<>(java.util.List.of("a", "b"));
    System.out.println(lb.get());
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.