Generic classes
A generic class has a type as a parameter: Box<T> is one class and Box<String> and Box<Integer> are two uses of it with a type argument fixed. The compiler checks every use against that argument, so the casts that old code needed are gone and the mistake that lesson 065 showed is a build error instead of a run-time one.
A type parameter
T is a name for a type the user of the class chooses. It appears in the field, in the parameter of set and in the return type of get, and the compiler keeps the three in agreement:
public class Boxes {
public static void main(String[] args) {
Box<String> text = new Box<>();
text.set("hello");
Box<Integer> number = new Box<>(42);
System.out.println(text.get() + " " + text.get().length());
System.out.println(number.get() + 1);
Box<Box<String>> nested = new Box<>(text);
System.out.println(nested.get().get());
}
}
class Box<T> {
private T value;
Box() {
}
Box(T value) {
this.value = value;
}
T get() {
return value;
}
void set(T value) {
this.value = value;
}
}
javac -Xlint:all Boxes.java
java Boxes
hello 5
43
hello
text.get().length() compiles because get returns a String for a Box<String>: the type argument reaches the method's return type. number.get() + 1 unboxes the Integer and adds, and the nested box needs two get calls because the value is a box.
The diamond
new Box<>() is the diamond: the type argument is taken from the variable on the left, so it is written once. It is not a raw type, which is why it produces none of the warnings of lesson 065; it is the same Box<String> with the argument inferred.
The diamond works where the compiler can infer every argument: an assignment, a return, a method argument. It does not work in an array creation (new Box<>[3] is illegal) or in a new expression whose type the compiler cannot see, and then the arguments are written out.
A bounded parameter
T extends Number restricts the argument to a subtype of Number, and then the body may call doubleValue. T extends Comparable<T> is the bound a sorting method needs, because it calls compareTo:
import java.util.List;
public class Bounded {
public static void main(String[] args) {
List<Integer> ints = List.of(3, 1, 2);
List<Double> doubles = List.of(1.5, 2.5);
System.out.println(sum(ints));
System.out.println(sum(doubles));
System.out.println(max(List.of("pear", "apple", "fig")));
}
static double sum(List<? extends Number> numbers) {
double total = 0;
for (Number number : numbers) {
total += number.doubleValue();
}
return total;
}
static <T extends Comparable<T>> T max(List<T> values) {
T best = values.get(0);
for (T value : values) {
if (value.compareTo(best) > 0) {
best = value;
}
}
return best;
}
}
javac -Xlint:all Bounded.java
java Bounded
6.0
4.0
pear
The sum accepts a list of any number type because ? extends Number admits List<Integer> and List<Double> alike. The maximum is pear because String.compareTo is alphabetical and p comes after a and f; the wildcard of the first method and the bound of the second are the subject of lesson 067.
Two parameters
A record may be generic too, and a generic static method inside it is how a pair is built without repeating the arguments. The record below has two type parameters and three methods that use them:
public class Pairs {
public static void main(String[] args) {
Pair<String, Integer> age = Pair.of("Ada", 36);
System.out.println(age);
System.out.println(age.first() + " is " + age.second());
Pair<Integer, String> swapped = age.swap();
System.out.println(swapped);
System.out.println(age.mapSecond(n -> n + 1));
}
}
record Pair<A, B>(A first, B second) {
static <A, B> Pair<A, B> of(A first, B second) {
return new Pair<>(first, second);
}
Pair<B, A> swap() {
return new Pair<>(second, first);
}
<C> Pair<A, C> mapSecond(java.util.function.Function<B, C> f) {
return new Pair<>(first, f.apply(second));
}
}
javac -Xlint:all Pairs.java
java Pairs
Pair[first=Ada, second=36]
Ada is 36
Pair[first=36, second=Ada]
Pair[first=Ada, second=37]
swap changes the order of the two parameters and mapSecond changes the type of the second one, so each returns a different Pair type. The generated toString of the record is the same in all three cases, which is why the types are visible only in the source.
The type that does not fit
The whole point of the parameter is this error. A Box<String> refuses an int at the call, before anything runs:
public class Wrong {
public static void main(String[] args) {
Box<String> box = new Box<>();
box.set(42);
System.out.println(box.get());
}
}
class Box<T> {
private T value;
void set(T value) {
this.value = value;
}
T get() {
return value;
}
}
javac -Xlint:all Wrong.java
Wrong.java:4: error: incompatible types: int cannot be converted to String
box.set(42);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
The error names the two types and the argument, and the note at the end is javac saying that it chose the shortest explanation: the call wanted a String because the variable is a Box<String>. With -Xdiags:verbose the same error explains that T was inferred as String from the declaration.
Exercises
- Add a map method to Box that returns a box of another type and print the result.
- Make sum accept a List<Integer> only and read the error the call with doubles gives.
- Give Pair a third type parameter and a triple factory.
- Write a Box<int> and explain the error in one sentence.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a type parameter?
Answer
A name for a type the user of the class chooses
Box<T> is one class, and each use fixes T to one type.
-
What does the diamond operator infer?
Answer
The type arguments, from the context of the new expression
new Box<>() takes its arguments from the variable or the call it is part of.
-
What does
<T extends Number>allow in the body?Answer
Calls to the methods of Number on a value of type T
The bound is the promise about T, so the methods of the bound can be called.
-
What does this program print?
public class Q1 { public static void main(String[] args) { Box<String> b = new Box<>(); b.set("x"); System.out.println(b.get() + b.get()); } } class Box<T> { private T value; void set(T value) { this.value = value; } T get() { return value; } }Answer
xx
The two get calls return the same String and the plus joins them.
-
What does this program print?
public class Q2 { public static void main(String[] args) { Box<Integer> b = new Box<>(10); System.out.println(b.get() * 2); } } class Box<T> { private final T value; Box(T value) { this.value = value; } T get() { return value; } }Answer
20
The return type is Integer, which unboxes for the multiplication.
-
What does this program print?
public class Q3 { public static void main(String[] args) { System.out.println(max(3, 7)); System.out.println(max("a", "b")); } static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) > 0 ? a : b; } }Answer
7 then b
The bound allows compareTo for both types, and each call gets the larger value.
-
What does this program print?
public class Q4 { public static void main(String[] args) { Pair<String, Integer> p = new Pair<>("a", 1); Pair<Integer, String> q = p.swap(); System.out.println(q.first() + 1); } } record Pair<A, B>(A first, B second) { Pair<B, A> swap() { return new Pair<>(second, first); } }Answer
2
The swap puts the Integer first, and adding one gives two.
-
What is the first line of the compiler output for this program?
public class Q5 { public static void main(String[] args) { Box<String> b = new Box<>(); b.set(1); } } class Box<T> { private T value; void set(T value) { this.value = value; } }Answer
error: incompatible types: int cannot be converted to String
T is String for this variable, so the int argument does not fit.
-
What does
Box<Box<String>>mean?Answer
A box whose value is a box of strings
Type arguments nest, and each level needs its own call to get.
-
Which situation is the diamond not allowed in?
Answer
An array creation such as
new Box<>[3]Arrays of generic types are not allowed at all, and the diamond needs an inferable context.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev