Skip to content
Justice Tech School

Java Generics

Generics let classes and methods work with many types safely. Bounded types use extends and wildcards use ? extends T. Type erasure removes them at runtime.

Example
import java.util.*;
public class Main {
    static class Box<T> { private T v; Box(T v) { this.v = v; } T get() { return v; } }
    static <T extends Comparable<T>> T max(List<T> l) { T m = l.get(0); for (T x : l) if (x.compareTo(m) > 0) m = x; return m; }
    public static void main(String[] args) {
        System.out.println(new Box<>("hi").get() + " " + max(List.of(3, 9, 4)) + " " + max(List.of("a", "c", "b")));
    }
}

Result

hi 9 c

Exercise

Bounded type.

<T  Comparable<T>>

Quiz Test

What does Box<T> allow?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.