Generics and Templates

Suppose you need a container that holds integers in one program and strings in another. Copying the class for each type duplicates every bug, and storing everything as Object forces casts that fail only when the program runs. Java generics and C++ templates solve this by letting you write a class or function once, with the element type left as a parameter that the user of the code fills in. You use them every time you declare an ArrayList< String > in Java or a std::vector< int > in C++.

Type parameters and type arguments

A type parameter is a placeholder name, conventionally T, declared in angle brackets and used in the body wherever a concrete type would appear. The type you supply when you use the code, such as String, is the type argument.


Java
public class Box< T > {
    private T item;
    public void put(T item) { this.item = item; }
    public T get() { return item; }
}

Box< String > label = new Box< >();
label.put("fragile");
String s = label.get();   // no cast needed
// label.put(42);         // rejected at compile time


The compiler now knows that label holds strings, so a mistaken put(42) becomes a compile-time error instead of a ClassCastException later. The empty brackets on the right are the diamond operator. In Java, type arguments must be reference types: write Box< Integer >, not Box< int >, and autoboxing converts the values for you.


C++ writes the same idea as a template, and its type arguments may be any type, including int:


C++
template < typename T >
class Box {
    T item;
public:
    void put(const T& x) { item = x; }
    T get() const { return item; }
};

Box< int > count;


Functions can be generic too. A Java generic method declares its parameter before the return type, as in static < T > T first(T[] xs), and a C++ function template begins with template < typename T >. In both languages the compiler usually infers T from the arguments of the call, so you write first(names) without spelling out the type.

Two implementations: erasure and instantiation

Java and C++ look similar in source code but compile generic code in opposite ways.


Java uses type erasure: after checking every use, the compiler replaces each type parameter with its bound, or with Object when there is no bound, and inserts casts where values come out. Only one compiled class exists, whatever type arguments the program uses, and the JVM never sees T.


C++ uses template instantiation: for each distinct type argument, the compiler generates and compiles a separate copy of the class or function with T replaced by the real type. Box< int > and Box< double > are unrelated types with their own machine code.


Diagram contrasting Java, where two uses of Box compile to one erased class, with C++, where two uses of Box produce two separate instantiations.


Question

Java generics

C++ templates

When are types checked?

At compile time, then erased

At compile time, for each instantiation

Compiled copies

One class for all type arguments

One per distinct type argument

Primitive type arguments

Not allowed; use wrapper classes

Allowed

Type information at run time

Lost: a Box of String and a Box of Integer share one class

Kept: each instantiation is its own type

Typical cost

Casts and boxing

Larger executables



Constraints on the type argument

A generic body can use only the operations it knows the type argument supports. With an unbounded Java T, that means the methods of Object. A bound widens the menu: in static < T extends Number > double total(List< T > xs), the body may call x.doubleValue(), and a call with a list of String is rejected.


C++ checks requirements when it instantiates instead. A template that computes a + b compiles for int and std::string but produces an error when instantiated with a type that has no +. Since C++20, concepts let you state such requirements up front, which gives clearer error messages.



What to remember

  • A type parameter is a placeholder that a type argument fills at each use.
  • Generics move type errors from run time to compile time and remove manual casts.
  • Java erases type parameters to their bound or Object; one class serves every type argument, and primitives need wrapper classes.
  • C++ instantiates a separate copy for each distinct type argument and accepts any type that supports the operations the body uses.
  • A bound or a concept states which operations the body may use on T.

Example: Instantiations and erasure in the same algorithm

A data-processing library needs the largest element of several arrays. The C++ version is a function template; assume the standard headers are included.


C++
template < typename T >
T largest(const T* a, int n) {
    T best = a[0];
    for (int i = 1; i < n; ++i)
        if (best < a[i]) best = a[i];
    return best;
}

int scores[] = {72, 88, 65, 91};
double prices[] = {4.5, 2.25, 9.75};
int ids[] = {7, 3};
std::string names[] = {"Lin", "Ade", "Mo"};

largest(scores, 4);
largest(prices, 3);
largest(ids, 2);
largest(names, 3);


The Java team stores single values in a generic class:


Java
public class Box< T > {
    private T item;
    public Box(T item) { this.item = item; }
    public T get() { return item; }
}

Box< Integer > a = new Box< >(12);
Box< String > b = new Box< >("bolt");
System.out.println(a.getClass() == b.getClass());


a) For each of the four calls to largest, state the type the compiler deduces for T, then find how many distinct instantiations of largest it generates.


The compiler performs template argument deduction: it matches each argument against the parameter type const T*. An array argument decays to a pointer to its first element, so T is the element type of the array.

  • largest(scores, 4): T is int.
  • largest(prices, 3): T is double.
  • largest(ids, 2): T is int again.
  • largest(names, 3): T is std::string.

The compiler generates one instantiation per distinct type argument, and a repeated type argument reuses the existing instantiation:


instantiations=∣{int, double, std::string}∣=3\text{instantiations} = \left|\{\text{int},\ \text{double},\ \text{std::string}\}\right| = 3


Four calls produce 3 instantiations, one each for int, double and std::string.


b) Find the value each call returns.


Every instantiation runs the same loop: best starts at a[0] and is replaced whenever best < a[i] is true.

  • scores: best starts at 72. At i = 1, 72 < 88 is true, so best becomes ________. At i = 2, 88 < 65 is false. At i = 3, 88 < 91 is true, so best becomes 91. The call returns 91.
  • prices: best starts at 4.5. At i = 1, 4.5 < 2.25 is false, so best stays ________. At i = 2, 4.5 < 9.75 is true, so the call returns 9.75.
  • ids: best starts at 7, and 7 < 3 is false, so the call returns 7.
  • names: std::string defines < as a lexicographic comparison. "Lin" < "Ade" is false because L comes after A, and "Lin" < "Mo" is true because L comes before M, so the call returns "Mo".

The std::string instantiation compiles only because std::string supports < and copying; the template body places those two requirements on every T.


c) For the Java code, state the type of the field item after erasure, how many Box classes exist at run time, and what the final line prints.


T has no bound, so erasure replaces it with Object: the compiled class declares private Object item; and get() returns Object. At each call site the compiler inserts a cast, so a.get() compiles to a call followed by a cast to ________.


The declarations for Integer and String are checked separately at compile time but share the single compiled Box class, so one Box class exists at run time. getClass() returns that same Class object for both a and b, so the comparison is true and the program prints true.


In C++, by contrast, a Box< int > and a Box< std::string > would be two distinct classes, each with its own compiled code.

Match each term used in generic programming with Java and C++ to the description that fits it. Each description is used exactly once.

Match each term
A.

The concrete type supplied where generic code is used, such as String in a list of strings

B.

The C++ compiler inferring T from the types of the arguments in a function call

C.

Java's removal of generic placeholders after compile-time checks, replacing each with its bound or Object

D.

A placeholder name such as T, declared by a generic class or function and used in its body

E.

Java's automatic conversion of an int value into an Integer object so it can be stored in a generic container

F.

C++ generating a separate concrete class or function for each distinct set of template arguments

Type erasure

Template instantiation

Template argument deduction

Type argument

Type parameter

Autoboxing

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A warehouse application uses this generic Java class to pair a product name with its stock count. Complete the sentences with the most specific declared return types, using simple Java class names.


Java
final class Entry< K, V > {
    private final K key;
    private final V value;

    Entry(K key, V value) {
        this.key = key;
        this.value = value;
    }

    K key() { return key; }
    V value() { return value; }
}


The following declaration appears inside a method:


Java
Entry< String, Integer > stock =
    new Entry< String, Integer >("markers", 24);


The declared return type of stock.key() is . The declared return type of stock.value() is .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A Java class is declared as public class Cache< T >. Inside one of its methods, obj is a parameter of type Object. Which of the following lines fail to compile because the type argument is erased? Select all that apply.

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice