Generics
Box<T> is a generic class — T is a placeholder filled in with a real type wherever Box is used, so Box<Integer> and Box<String> are both valid, type-safe instantiations of the exact same class, with the compiler catching any type mismatch at the call site.
Main.java
Try it yourself →public class Main {
static class Box<T> {
private T value;
Box(T value) {
this.value = value;
}
T getValue() {
return value;
}
}
public static void main(String[] args) {
Box<Integer> intBox = new Box<>(42);
Box<String> strBox = new Box<>("hello");
System.out.println(intBox.getValue());
System.out.println(strBox.getValue());
}
}Output
42 hello
Generic methods
A method can be generic on its own, independent of its class — <T> before the return type declares first(T a, T b) works for any single type T, with the compiler inferring T from the arguments at the call site, no explicit type needed.
Main.java
Try it yourself →public class Main {
static <T> T first(T a, T b) {
return a;
}
public static void main(String[] args) {
System.out.println(first(10, 20));
}
}Output
10
Next: the Collections Framework — HashMap and HashSet, two of Java's standard collection types.
Practice exercise
Define a generic class Box<T> with a value field and a getValue() method. Create a Box<String> holding "hello", then print its value.