Intermediate 8 min

Generics and type parameters

A generic type lets one class or method work with several types while preserving type checks.

How it works

The type inside angle brackets describes an allowed element type. When you read from List<String>, you do not have to guess what was added. The compiler uses the type on both sides, rejecting the wrong additions and letting a read be used directly as a String.

Walk through an example

A List<String> accepts strings and gives you a string when you read an element. List<Integer> uses the same list operations with boxed integers.

What to watch for

List<Integer> and List<Number> are different types. If a method only reads numbers, it can accept List<? extends Number>.

Code example

public class Main {
    public static void main(String[] args) {
        java.util.List<String> names = new java.util.ArrayList<>();
        names.add("Mira");
        System.out.println(names.get(0));
    }
}

Check your understanding

Why does the compiler flag this line?

See the example and explanation
Worked example
Given List<String> names = new ArrayList<>(); names.add(5);
Answer The list expects String elements.

The type parameter checks each addition before execution. An integer does not satisfy the declared String type.

Open practice problem
Next lessonMaps and sets