Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Generics in Java

Generics in Java: Generics provide compile-time checking, while type erasure removes most type arguments and inserts casts or bridge methods; generic method inference derives arguments from parameters and the target type.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

generics

Generics provide compile-time checking, while type erasure removes most type arguments and inserts casts or bridge methods; generic method inference derives arguments from parameters and the target type.

Use ? extends T for a producer, ? super T for a consumer, the unbounded wildcard ? for an unknown type, and intersection bounds such as <T extends A & B> when both contracts are required.

Generic types are invariant; raw types discard checks, and non-reifiable varargs can expose an object under the wrong type through heap pollution.

Capture conversion lets a generic helper operate safely on List.

The output shows ? super insertion, a capture-helper swap, an intersection-bounded maximum, and String inferred for first.

Examples

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    static <T> T first(List<? extends T> values) {
        return values.get(0);
    }

    static void addInt(List<? super Integer> values, int value) {
        values.add(value);
    }

    static void swapFirstTwo(List<?> values) {
        swapCaptured(values);
    }

    private static <T> void swapCaptured(List<T> values) {
        Collections.swap(values, 0, 1);
    }

    static <T extends Number & Comparable<T>> T max(T left, T right) {
        return left.compareTo(right) >= 0 ? left : right;
    }

    public static void main(String[] args) {
        List<Number> numbers = new ArrayList<>(List.of(1, 2.5));
        addInt(numbers, 3);
        var words = new ArrayList<>(List.of("a", "b"));
        swapFirstTwo(words);
        String inferred = first(words);
        System.out.println(numbers);
        System.out.println(words);
        System.out.println(max(4, 7));
        System.out.println(inferred);
    }
}

Result

[1, 2.5, 3]
[b, a]
7
b

The output shows ? super insertion, a capture-helper swap, an intersection-bounded maximum, and String inferred for first.

Sources