Generics in Java

Generics let a class or method work with many types while the compiler still checks that you use them consistently: a List accepts only strings, and reading from it needs no cast. They were added in Java 5 and are checked only at compile time, which explains both their power and their odd restrictions. This page shows why generics exist, how to write generic classes and methods, the rules javac enforces, wildcards and bounds, and what erasure leaves at run time.

Contents

Why generics exist

Before Java 5, collections held Object. Any value could be added, every read needed a cast, and putting the wrong type in a list was only discovered when some other code read it back and the cast failed. Generics add a type parameter, such as the E in List<E>, which the user fills in with a type argument: List<String>. The compiler then checks every add and inserts the casts on every read for you.

Generics vocabulary
TermExampleMeaning
Generic typeclass Box<T>A class or interface with type parameters
Parameterized typeBox<String>A generic type with its type arguments filled in
Generic method<T> T max(List<T> items)A method with its own type parameter, usually inferred
Bounded type parameter<T extends Number>T must be Number or a subtype
WildcardList<?>, List<? extends Number>"Some type" that the code does not name
Raw typeListA generic type used without arguments; exists only for old code
ErasureType arguments are removed after compilation

By convention, type parameters are single capital letters: T for type, E for element, K and V for key and value, R for result.

Generic classes, generic methods and raw types

The program defines a generic Box, a generic max method that works for any comparable type, and then shows what goes wrong with a raw List. The two inputs to max were chosen so that numbers and strings are compared by their own natural order: 17 is the largest number, and "plum" comes last alphabetically.

Java
import java.util.ArrayList;
import java.util.List;

public class WhyGenerics {

    // A generic class: T is chosen by whoever creates a Box
    static class Box<T> {
        private T value;

        void put(T value) {
            this.value = value;
        }

        T get() {
            return value;
        }
    }

    // A generic method: T is inferred from the arguments
    static <T extends Comparable<T>> T max(List<T> items) {
        T best = items.get(0);
        for (T item : items) {
            if (item.compareTo(best) > 0) {
                best = item;
            }
        }
        return best;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    static void rawTypeProblem() {
        List raw = new ArrayList();               // no type argument: a raw type
        raw.add("text");
        raw.add(42);                              // nothing stops this
        try {
            for (Object o : raw) {
                String s = (String) o;            // the cast fails at run time
                System.out.println("raw list item: " + s);
            }
        } catch (ClassCastException e) {
            System.out.println("raw list: ClassCastException on the second element");
        }
    }

    public static void main(String[] args) {
        Box<String> names = new Box<>();
        names.put("Ada");
        String n = names.get();                   // no cast needed
        System.out.println("box holds " + n);
        // names.put(42);                         would not compile: 42 is not a String

        System.out.println("max of numbers: " + max(List.of(3, 17, 8)));
        System.out.println("max of words:   " + max(List.of("pear", "apple", "plum")));

        rawTypeProblem();
    }
}

Output:

Output
box holds Ada
max of numbers: 17
max of words:   plum
raw list item: text
raw list: ClassCastException on the second element
  • Box<String> returns a String from get with no cast, and names.put(42) would be a compile error, not a run-time surprise.
  • max declares its own type parameter, <T extends Comparable<T>>. The bound says T must be comparable to itself, which is what lets the body call compareTo. The compiler inferred T as Integer for the first call and String for the second.
  • The raw List accepted both a string and the number 42; the cast failed only when the list was read. That is the pre-Java 5 situation generics were designed to remove. javac warns about raw types with -Xlint:rawtypes; the method suppresses the warning to show the problem.

The rules javac enforces

Generics are checked by the compiler, and some things that look natural are not allowed. The program compiles a class that breaks seven rules and prints javac's errors; the numbers in the source comments help match each error to its line.

Java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.tools.ToolProvider;

// Compiles code that breaks the rules of generics and prints javac's errors
public class GenericRules {

    static final String SOURCE = """
            import java.util.ArrayList;
            import java.util.List;

            class Rules<T> {
                static T shared;                                // 1: static field of type T
                T make() { return new T(); }                    // 2: new T()
                T[] array() { return new T[10]; }               // 3: generic array creation
                boolean check(Object o) { return o instanceof T; }   // 4: instanceof T

                void variance(List<Integer> ints, List<? extends Number> nums) {
                    List<Number> n = ints;                      // 5: not a subtype
                    nums.add(Integer.valueOf(1));               // 6: cannot add to ? extends
                }

                List<int> primitives;                           // 7: primitive type argument
            }
            """;

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("generics");
        Path file = dir.resolve("Rules.java");
        Files.writeString(file, SOURCE);
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        ToolProvider.getSystemJavaCompiler().run(null, null,
                new PrintStream(err, true, StandardCharsets.UTF_8),
                "-d", dir.toString(), file.toString());
        err.toString(StandardCharsets.UTF_8).lines()
                .filter(l -> l.startsWith(file.toString()))
                .map(l -> l.substring(dir.toString().length() + 1))
                .map(l -> l.length() > 98 ? l.substring(0, 95) + "..." : l)
                .forEach(System.out::println);
    }
}

Output:

Output
Rules.java:5: error: non-static type variable T cannot be referenced from a static context
Rules.java:15: error: unexpected type
Rules.java:6: error: unexpected type
Rules.java:7: error: generic array creation
Rules.java:8: error: Object cannot be safely cast to T
Rules.java:11: error: incompatible types: List<Integer> cannot be converted to List<Number>
Rules.java:12: error: incompatible types: Integer cannot be converted to CAP#1
  1. Line 5: a static field cannot have type T, because there is one static field per class, shared by Rules<String> and Rules<Integer>.
  2. Line 6: new T() is impossible: at run time T is erased, so the JVM would not know which class to create. Pass a Supplier<T> (for example Box::new) or a Class<T> instead.
  3. Line 7: "generic array creation": an array must know its element type at run time, which T cannot provide. Use a List<T>, or let the caller pass an array, as Collection.toArray(T[]) does.
  4. Line 8: instanceof T cannot be checked for the same reason.
  5. Line 11: a List<Integer> is not a List<Number>, even though every Integer is a Number. If it were, code could add a Double to the list of integers through the List<Number> reference. Generic types are invariant; arrays, which are covariant, check this only at run time with ArrayStoreException.
  6. Line 12: nothing can be added to a List<? extends Number>, because the list might really be a List<Double>. javac names the unknown type CAP#1 ("capture of ?").
  7. Line 15: type arguments must be reference types: List<int> is not allowed, which is why autoboxing exists.

Wildcards and PECS

Because generic types are invariant, a method that takes List<Number> refuses a List<Integer>. Wildcards make such methods flexible. The program writes one method that reads numbers, one that adds integers, and one that does not care about the element type, then calls each with several list types.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class Wildcards {

    // ? extends Number: read Numbers from it (a producer)
    static double sum(Collection<? extends Number> numbers) {
        double total = 0;
        for (Number n : numbers) {
            total += n.doubleValue();
        }
        return total;
    }

    // ? super Integer: write Integers into it (a consumer)
    static void addRange(List<? super Integer> target, int count) {
        for (int i = 1; i <= count; i++) {
            target.add(i);
        }
    }

    // ? alone: the method does not care about the element type
    static int countNulls(Collection<?> items) {
        int nulls = 0;
        for (Object o : items) {
            if (o == null) {
                nulls++;
            }
        }
        return nulls;
    }

    public static void main(String[] args) {
        List<Integer> ints = List.of(1, 2, 3);
        List<Double> doubles = List.of(1.5, 2.5);
        System.out.println("sum ints: " + sum(ints) + ", sum doubles: " + sum(doubles));

        List<Number> numbers = new ArrayList<>();
        List<Object> objects = new ArrayList<>();
        addRange(numbers, 3);
        addRange(objects, 2);
        System.out.println("into List<Number>: " + numbers);
        System.out.println("into List<Object>: " + objects);

        System.out.println("nulls: " + countNulls(Arrays.asList("a", null, "b", null)));

        // List<Integer> is NOT a List<Number>, even though Integer is a Number
        // List<Number> bad = ints;              would not compile
        List<? extends Number> ok = ints;         // a read-only view of "some Number type"
        System.out.println("first via wildcard: " + ok.get(0));
    }
}

Output:

Output
sum ints: 6.0, sum doubles: 4.0
into List<Number>: [1, 2, 3]
into List<Object>: [1, 2]
nulls: 2
first via wildcard: 1
  • sum(Collection<? extends Number>) accepted both a List<Integer> and a List<Double>: everything read from it is at least a Number.
  • addRange(List<? super Integer>) accepted a List<Number> and a List<Object>: any list that can hold an Integer is fine to write into.
  • Collection<?> accepts any collection when the code only needs Object methods, such as checking for null.
  • The rule of thumb is PECS, "producer extends, consumer super": a parameter you read from uses ? extends T, a parameter you write into uses ? super T, and one you both read and write uses plain T. Collections.copy(List<? super T> dest, List<? extends T> src) is the textbook example.

Bounds, Comparable and inference

Bounds restrict which type arguments are allowed. The program uses an Apple that inherits Comparable<Fruit> from its parent, which a naive bound rejects, a type parameter with two bounds, a generic record whose method changes one of its type parameters, and type inference.

Java
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

public class BoundsAndInference {

    static class Fruit implements Comparable<Fruit> {
        final int weight;

        Fruit(int weight) {
            this.weight = weight;
        }

        @Override
        public int compareTo(Fruit other) {
            return Integer.compare(weight, other.weight);
        }

        @Override
        public String toString() {
            return getClass().getSimpleName() + "(" + weight + ")";
        }
    }

    static class Apple extends Fruit {        // an Apple is Comparable<Fruit>, not <Apple>
        Apple(int weight) {
            super(weight);
        }
    }

    // Accepts Apple, because Apple implements Comparable<Fruit> and Fruit is a supertype
    static <T extends Comparable<? super T>> T heaviest(List<T> items) {
        T best = items.get(0);
        for (T item : items) {
            if (item.compareTo(best) > 0) {
                best = item;
            }
        }
        return best;
    }

    // Two bounds: T must be a Number AND Comparable
    static <T extends Number & Comparable<T>> double spread(List<T> values) {
        return Collections.max(values).doubleValue() - Collections.min(values).doubleValue();
    }

    // A generic record and a generic method that changes the type parameter
    record Pair<A, B>(A first, B second) {
        <C> Pair<A, C> mapSecond(Function<? super B, ? extends C> f) {
            return new Pair<>(first, f.apply(second));
        }
    }

    public static void main(String[] args) {
        List<Apple> apples = List.of(new Apple(150), new Apple(210), new Apple(180));
        System.out.println("heaviest apple: " + heaviest(apples));
        System.out.println("Collections.max: " + Collections.max(apples));
        System.out.println("spread of ints: " + spread(List.of(4, 19, 7)));

        Pair<String, Integer> p = new Pair<>("width", 1920);         // diamond infers types
        Pair<String, String> q = p.mapSecond(px -> px / 96 + " inches");
        System.out.println(p + " -> " + q);

        // Inference needs a hint when nothing tells it the type
        List<String> empty = Collections.emptyList();                 // inferred from target
        var explicit = Collections.<String>emptyList();               // type witness
        System.out.println("empty lists: " + empty + " " + explicit);
    }
}

Output:

Output
heaviest apple: Apple(210)
Collections.max: Apple(210)
spread of ints: 15.0
Pair[first=width, second=1920] -> Pair[first=width, second=20 inches]
empty lists: [] []
  • Apple implements Comparable<Fruit>, not Comparable<Apple>. With the bound T extends Comparable<T>, as in the earlier max, calling it with a List<Apple> does not compile: javac reports "method max cannot be applied to given types". The bound T extends Comparable<? super T> accepts any type comparable to itself or to a supertype, so heaviest found the 210 g apple. This is why Collections.max has that strange-looking signature.
  • <T extends Number & Comparable<T>> requires both: the method can call doubleValue() and pass the list to Collections.max. A class bound, if any, must come first.
  • The diamond new Pair<>(...) (Java 7) inferred <String, Integer> from the variable's type. mapSecond introduced a new type parameter C, inferred from the lambda's result, to turn a Pair<String, Integer> into a Pair<String, String>.
  • When there is nothing to infer from, as with var x = Collections.emptyList(), the result would be a List<Object>. A type witness, Collections.<String>emptyList(), states the type explicitly.

Erasure: what is left at run time

Generics are implemented by type erasure: the compiler checks the types, then replaces each type parameter by its bound (Object if it has none) and inserts casts. The program compares the classes of two differently parameterized lists and creates a typed array from a list.

Java
import java.util.ArrayList;
import java.util.List;

public class Erasure {

    // Type arguments exist only at compile time
    static <T> T[] toArray(List<T> list, T[] target) {
        return list.toArray(target);   // new T[] is impossible, so the caller passes an array
    }

    public static void main(String[] args) {
        List<String> strings = new ArrayList<>();
        List<Integer> integers = new ArrayList<>();
        boolean same = strings.getClass() == integers.getClass();
        System.out.println("same class at run time: " + same);
        System.out.println("class: " + strings.getClass().getName());

        // instanceof List<String> is not allowed; only List<?> can be checked
        Object o = strings;
        System.out.println("o instanceof List<?>: " + (o instanceof List<?>));

        strings.add("x");
        String[] arr = toArray(strings, new String[0]);
        System.out.println("array type: " + arr.getClass().getSimpleName());
    }
}

Output:

Output
same class at run time: true
class: java.util.ArrayList
o instanceof List<?>: true
array type: String[]
  • List<String> and List<Integer> are the same class at run time, java.util.ArrayList. The type arguments are not stored in the objects.
  • instanceof List<?> is allowed because it asks only "is it a List?", which the JVM can answer.
  • Since T is erased, toArray asks the caller for an array of the right type and uses its class to create the result: a real String[].
  • Erasure was chosen so that generic code and pre-Java 5 code could run together without changing the JVM. Its consequences, including bridge methods, unchecked casts and heap pollution, are on the type erasure page. Generic information is still kept in class files for declarations, so reflection can read the declared type of a field such as List<String> names.

Guidelines

Writing generic code
SituationUse
A method parameter you only read from? extends T
A method parameter you only write into? super T
Return typesConcrete types, never wildcards; callers should not have to deal with ?
Sorting or comparing elements<T extends Comparable<? super T>>, or take a Comparator<? super T>
Creating instances of TTake a Supplier<T> or Class<T>
Arrays of TUse List<T> instead
Raw typesNever in new code; fix the rawtypes and unchecked warnings
Generic varargs methodsMark safe ones @SafeVarargs; see varargs