Skip to content
KALANBLON
Show contents

Chapter 1 of 7 · 20 min

Generics in depth

By the end of this chapter, you'll be able to

  • Write a generic class and a generic method
  • Bound a type parameter with extends
  • Choose between ? extends and ? super depending on whether the collection produces or consumes
  • Explain type erasure and its consequences

Generic classes and methods

A type parameter (T, A, K…) is a variable that stands for a type. It is declared between angle brackets, on the class or before a method's return type:

record Pair<A, B>(A first, B second) {
    Pair<B, A> swap() {
        return new Pair<>(second, first);
    }
}

<T extends Comparable<? super T>> T largest(List<T> elements) {
    if (elements.isEmpty()) {
        throw new IllegalArgumentException("empty list");
    }
    T best = elements.getFirst();
    for (T e : elements) {
        if (e.compareTo(best) > 0) {
            best = e;
        }
    }
    return best;
}

double sum(List<? extends Number> numbers) {
    double total = 0;
    for (Number n : numbers) {
        total += n.doubleValue();
    }
    return total;
}

void fill(List<? super Integer> target, int n) {
    for (int i = 1; i <= n; i++) {
        target.add(i);
    }
}

void main() {
    Pair<String, Integer> p = new Pair<>("Nairobi", 4_400_000);
    IO.println(p + " -> " + p.swap());

    IO.println(largest(List.of(3, 17, 8)));
    IO.println(largest(List.of("kiwi", "mango", "banana")));

    IO.println(sum(List.of(1, 2, 3)) + " " + sum(List.of(0.5, 1.25)));

    List<Number> numbers = new ArrayList<>();
    fill(numbers, 3);
    numbers.add(2.5);
    IO.println(numbers);
}
Pair[first=Nairobi, second=4400000] -> Pair[first=4400000, second=Nairobi]
17
mango
6.0 1.75
[1, 2, 3, 2.5]
  • Pair<A, B> works with any types; new Pair<>(…) lets the compiler infer the types (the "diamond" operator).
  • <T extends Comparable<? super T>> is a bound: T must know how to compare itself. largest therefore accepts Integer and String, but would reject a list of Pair. The ? super T also allows types whose parent implements Comparable.
  • List<? extends Number> accepts a List<Integer> or a List<Double>: you can read Number values, but not add elements (the exact type is unknown).
  • List<? super Integer> accepts a List<Integer>, List<Number> or List<Object>: you can add Integer values.

Producing or consuming: the PECS rule

The mnemonic PECS (Producer Extends, Consumer Super) settles it every time:

The collection…WildcardExample
produces values you read? extends Tsum(List<? extends Number>)
consumes values you add? super Tfill(List<? super Integer>)
does bothexact T, no wildcardvoid sort(List<T>)

That's exactly the signature of Collections.copy(List<? super T> dest, List<? extends T> src) in the standard library: the source produces, the destination consumes.

Type erasure

Generics exist only during compilation. The compiler checks the types, then erases them: at run time, a List<String> and a List<Integer> are both plain Lists. This is called type erasure, a choice made to stay compatible with pre-2004 Java.

At run time, a single class: impossible to write new T() or instanceof List<String>.

Step 5 of 5
Text description of the animation
  1. In the source code, the types are precise.
  2. The compiler checks every use: impossible to treat first as a number.
  3. A dangerous assignment is rejected here, before anything runs.
  4. In the bytecode, A and B become Object; a T bounded by Comparable becomes Comparable.
  5. At run time, a single class: impossible to write new T() or instanceof List<String>.

Practical consequences: you can't write new T(), nor new T[10], nor test x instanceof List<String>. If a method really needs the type at run time, pass it a Class<T> parameter.

Your turn

Worked exercise

Solved exercise: the key of the largest value

Write a generic method keyOfMax(Map<K, V> table) that returns the key associated with the largest value, in an empty Optional if the table is empty. It must work with any key type and any comparable value type. Test it with cities and their population, with integer codes mapped to animal names, then with an empty table.

Hint 1
Two type parameters: <K, V extends Comparable<? super V>>. Only the value needs to be comparable.
Hint 2
Walk through table.entrySet(), keeping the best entry seen so far; Optional.ofNullable(key) returns an empty Optional if key is null.
Show the solution and common mistakes
<K, V extends Comparable<? super V>> Optional<K> keyOfMax(Map<K, V> table) {
    K bestKey = null;
    V max = null;
    for (Map.Entry<K, V> e : table.entrySet()) {
        if (max == null || e.getValue().compareTo(max) > 0) {
            bestKey = e.getKey();
            max = e.getValue();
        }
    }
    return Optional.ofNullable(bestKey);
}

void main() {
    Map<String, Integer> population = new TreeMap<>(Map.of("Kigali", 1_700_000, "Quito", 2_800_000, "Hanoi", 8_400_000));
    IO.println(keyOfMax(population).orElse("none"));
    Map<Integer, String> codes = Map.of(1, "zebra", 2, "antelope");
    IO.println(keyOfMax(codes).orElse(-1));
    IO.println(keyOfMax(new HashMap<String, Double>()).orElse("none"));
}
Hanoi
1
none

For the codes, the values are Strings: "zebra" is the greatest in alphabetical order, hence the key 1. The same method serves two very different uses, and the compiler checks both.

Common mistakes:

  • Writing <K, V> without a bound: compareTo doesn't exist on an arbitrary V, and the code doesn't compile.
  • Returning null instead of an empty Optional: the caller forgets the empty-table case and gets a NullPointerException further on.

Summary

  1. 1A type parameter (<T>) makes a class or method reusable, with compile-time checking.
  2. 2extends bounds a type parameter: <T extends Comparable<? super T>> requires a comparable type.
  3. 3PECS: ? extends for a collection you read, ? super for a collection you fill.
  4. 4Generics are invariant: a List<String> isn't a List<Object>.
  5. 5Types are erased at run time: no new T(), no instanceof List<String>.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.