Generics and templates: Java and C++
Both languages let one class hold a value of any type and one function pick the largest of a list, with the type written once. The resemblance stops at the compiler: a C++ template is a recipe that is compiled again for every type it is used with, and a Java generic is a single class with the type arguments erased and casts inserted. This page runs the Java version and shows the C++ one.
The task
A box that holds one value, a method that returns the first element of a list, and a method that returns the largest, which needs the elements to be comparable. All three are written once and used with strings and with integers, and the program also asks the two list objects what class they are, because the answer is the difference.
The Java version
Box<T> is a generic class, <T> T first(List<T>) is a generic method, and <T extends Comparable<T>> is a bounded one: the bound is what lets the body call compareTo, and the compiler rejects a call whose type does not satisfy it:
import java.util.ArrayList;
import java.util.List;
public class Boxes {
static class Box<T> {
private final T value;
Box(T value) {
this.value = value;
}
T get() {
return value;
}
}
static <T> T first(List<T> values) {
return values.get(0);
}
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;
}
public static void main(String[] args) {
Box<String> text = new Box<>("text");
Box<Integer> number = new Box<>(42);
System.out.println("box: " + text.get());
System.out.println("number: " + number.get());
System.out.println("first: " + first(List.of(3, 1, 2)));
System.out.println("max: " + max(List.of(3, 1, 2)));
System.out.println("max of words: " + max(List.of("pear", "apple", "fig")));
List<String> strings = new ArrayList<>();
List<Integer> integers = new ArrayList<>();
System.out.println("same class: " + (strings.getClass() == integers.getClass()));
System.out.println("name: " + strings.getClass().getSimpleName());
}
}
javac -Xlint:all -d out Boxes.java
java -cp out Boxes
box: text
number: 42
first: 3
max: 3
max of words: pear
same class: true
name: ArrayList
One class after erasure
The sixth line is the one a C++ programmer does not expect: List<String> and List<Integer> are the same class at run time. The compiler erases the type argument, inserts the casts that make the values safe to use, and keeps the argument only in the signature of the source. There is one ArrayList in the class file, not one per element type.
Three consequences follow, and each is a line of a Java program that will not compile. A generic cannot be instantiated with a primitive, so Box<int> is an error and Box<Integer> is the form. A generic array cannot be created, so new Box<String>[10] is an error. And instanceof List<String> is an error, because at run time the question has no answer.
The C++ version
The C++ template is a recipe. Box<std::string> and Box<int> are two classes, each compiled from the template for its argument, and max is a function template that uses operator> and is checked when it is instantiated. This block is not compiled here, because the image has no g++:
#include <iostream>
#include <string>
#include <vector>
template <typename T>
class Box {
public:
explicit Box(T value) : value_(std::move(value)) {
}
const T& get() const {
return value_;
}
private:
T value_;
};
template <typename T>
T max(const std::vector<T>& values) {
T best = values.at(0);
for (const T& value : values) {
if (best < value) {
best = value;
}
}
return best;
}
int main() {
Box<std::string> text("text");
Box<int> number(42);
std::cout << "box: " << text.get() << '\n';
std::cout << "number: " << number.get() << '\n';
std::cout << "max: " << max(std::vector<int>{3, 1, 2}) << '\n';
std::cout << "max of words: " << max(std::vector<std::string>{"pear", "apple", "fig"}) << '\n';
}
The C++ program prints the first five lines of the Java output and has no analogue of the last two: the question getClass() answers does not exist, because each instantiation is a class of its own with a name the compiler chose. A type error in max appears when the function is instantiated for a type without operator<, which may be in a header far from the call.
What differs and why
The Java generic is checked once, at the definition, against the bound. A method with extends Comparable<T> compiles or does not compile before any call exists, and every call is checked against the same rule. The C++ template is checked at each instantiation, which is why a template can accept a type the author never imagined and why the error arrives with the call in the message.
That difference explains the two styles. A C++ template lives in a header, because the compiler needs the body at every call. A Java generic lives in a class file, because the body is compiled once and the type argument is gone. A C++ programmer reaches for constexpr, if constexpr and specialisation to make one template behave differently per type; the Java answer is overloading, a strategy object or a visitor, because the erased body cannot see the type.
The price of erasure is the cast at the use site, which the compiler inserts and which cannot fail for a well-typed program. The price of instantiation is code size and compile time: a template used with ten types is ten functions in the binary, and the error messages of a deep template are famously long. Java chose the smaller binary and the earlier check; C++ chose the specialisation.
The habit that breaks
The habit is to expect the type argument at run time. A C++ programmer writes a function that takes Box<T>, looks at typeid(T) or overloads on the template argument, and then writes the same thing in Java with instanceof T or new T(). Neither compiles, and the reason is the same: the type argument is not there.
The Java answer is to pass the class object, Class<T>, when the code needs the type at run time. A factory takes Supplier<T> or a Class<T> and calls it, and a check takes a predicate. The type parameter is a compile-time contract, and a program that needs it at run time says so in the signature instead of hoping the compiler kept it.
The next page
The next page is strings: an immutable String against a mutable std::string, and the append that one language allows on a value and the other only on a builder. The C++ lesson is function templates, and the Java lesson is generics.
The Java program was compiled with OpenJDK 21.0.13 (javac) and run on Alpine Linux in a Docker container. The C++ program is shown and was not compiled here: the image has no g++.
Article author: Arthur Isaev