DEV Community

Adetayo Akinsanya
Adetayo Akinsanya

Posted on Originally published at unkletayo.dev on

Generics: writing code that works for more than one type

Generics: writing code that works for more than one type

Suppose you need a simple container that holds a single value and lets you read it back. For integers:

public class IntBox {
    private int value;
    public IntBox(int value) { this.value = value; }
    public int get() { return this.value; }
}

Enter fullscreen mode Exit fullscreen mode

Then you need the same thing for strings. And doubles. And accounts. You write StringBox, DoubleBox, AccountBox. Each class is identical except for the type name.

There is a better way. Generics let you write the container once and use it with any type:

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

Enter fullscreen mode Exit fullscreen mode

T is a type parameter : a placeholder that the caller fills in when they use the class. Box<String> is Box where T is String. Box<Integer> is Box where T is Integer. The same class, the same logic, two distinct types at the call site.

How type parameters work

A type parameter is declared in angle brackets after the class name: class Box<T>. Inside the class, T is usable as if it were a real type. Fields can be of type T. Methods can return T. Constructors can take T as a parameter.

The caller provides the actual type when constructing an instance:

Box<String> nameBox = new Box<>("Adetayo");
Box<Integer> countBox = new Box<>(42);

Enter fullscreen mode Exit fullscreen mode

The compiler now knows that nameBox.get() returns a String and countBox.get() returns an Integer. You do not need a cast:

String name = nameBox.get(); // no cast needed
Integer count = countBox.get(); // no cast needed

Enter fullscreen mode Exit fullscreen mode

Before generics (Java 1.4 and earlier), collections held Object. Every retrieval required a cast, and a wrong cast caused ClassCastException at runtime. With generics, the wrong type is a compiler error:

Box<Integer> box = new Box<>(42);
String s = box.get(); // compile error: incompatible types

Enter fullscreen mode Exit fullscreen mode

The error appears at compile time, not at runtime. That is the core value of generics: type mistakes that would previously crash your program at runtime become errors the compiler catches during the build.

Type inference

You can often omit the type argument on the right side of a declaration, and the compiler infers it from the left side. This is called the diamond operator :

Box<String> nameBox = new Box<>("Adetayo"); // compiler infers Box<String>

Enter fullscreen mode Exit fullscreen mode

The diamond <> tells the compiler to infer the type parameter from context. When inference is unambiguous, using the diamond makes the code less repetitive. When the type is not obvious from context, writing it out is clearer.

Multiple type parameters

A class can have more than one type parameter:

public class Pair<A, B> {
    private final A first;
    private final B second;

    public Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    public A getFirst() { return first; }
    public B getSecond() { return second; }
}


Pair<String, Integer> entry = new Pair<>("totalItems", 42);
System.out.println(entry.getFirst()); // "totalItems"
System.out.println(entry.getSecond()); // 42

Enter fullscreen mode Exit fullscreen mode

By convention, single-letter uppercase names are used for type parameters: T for a general type, K and V for key and value in maps, E for element in collections, R for a return type in functions. These conventions are not enforced; they communicate intent.

Bounded type parameters

A type parameter can require that the actual type satisfy a constraint. <T extends Comparable<T>> means "T must implement Comparable<T>":

public static <T extends Comparable<T>> T max(T a, T b) {
    return a.compareTo(b) >= 0 ? a : b;
}

Enter fullscreen mode Exit fullscreen mode

Without the bound, the compiler rejects a.compareTo(b) because it has no guarantee that T has that method. With the bound, compareTo is available because any type that satisfies extends Comparable<T> is guaranteed to implement it.

System.out.println(max("apple", "banana")); // banana
System.out.println(max(10, 7)); // 10

Enter fullscreen mode Exit fullscreen mode

The constraint is checked at the call site. max(new Object(), new Object()) would fail to compile because Object does not implement Comparable.

Bounds can combine multiple interfaces with &:

public <T extends Serializable & Comparable<T>> void process(T item) { ... }

Enter fullscreen mode Exit fullscreen mode

T must implement both Serializable and Comparable<T>. Classes come before interfaces in the bound list; a class bound, if present, must be first.

Generic methods

A generic method declares its own type parameter, independent of the class. You saw this with max above. The type parameter is declared before the return type:

public static <T> void swap(T[] array, int i, int j) {
    T temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

Enter fullscreen mode Exit fullscreen mode

The caller does not need to provide the type argument explicitly; the compiler infers it from the array type:

String[] words = {"hello", "world"};
swap(words, 0, 1);
System.out.println(Arrays.toString(words)); // [world, hello]

Enter fullscreen mode Exit fullscreen mode

A method can be generic even if its class is not. This is the right choice when the type parameter is local to that one operation and does not appear in any field.

What you cannot do with a type parameter

There are four restrictions that follow from how Java implements generics. All four are covered in depth in the next article on erasure, but it helps to see them now.

You cannot create an instance: new T() is a compile error. The compiler does not know what constructor T has, because T could be any type.

You cannot create an array of a generic type: new T[10] is a compile error. This is a consequence of how Java arrays track their component type at runtime; type parameters are not available at runtime.

You cannot use a type parameter in a static context. static T defaultValue is a compile error. Static members belong to the class, not to any particular parameterized use of the class.

You cannot test with instanceof T: x instanceof T is a compile error. The runtime does not have type information for T after compilation.

Each restriction has a workaround, and understanding erasure explains why they exist. That is the subject of a later article.

Prediction exercise

public static <T> List<T> repeat(T item, int times) {
    List<T> result = new ArrayList<>();
    for (int i = 0; i < times; i++) {
        result.add(item);
    }
    return result;
}

Enter fullscreen mode Exit fullscreen mode

What does repeat("x", 3) return? What does repeat(null, 2) return? Then: does repeat(42, 3) compile? If so, is the return type List<Integer> or List<int>? The next article covers wildcards, the extends and super bounds you use with them, and why you need a different kind of bound when you are reading from a collection versus writing to one. Generics: wildcards and variance continues from here.

Top comments (0)