Generics and type parameters

Why does the compiler flag this line?

Examples

Worked example

Input
List<String> names = new ArrayList<>(); names.add(5);
Expected output
The list expects String elements.

Hints and solution

Hint 1

Write down the starting state and walk through one example by hand.

Reveal worked answer

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

Back to the lesson