Thuta Learning
Java
AdvancedProgrammingbeginner

Generics

What you'll walk away with

  • Explain the language and JVM behavior behind Generics
  • Test normal, boundary, invalid, and failure cases
  • Write maintainable and testable Java

A type parameter lets one algorithm preserve the caller's element type without unsafe casts.

Build a Complete Mental Model

Generics provide compile-time type safety and reusable algorithms. Java generics are invariant; use producer extends and consumer super (PECS), and account for runtime limitations caused by type erasure.

Apply It in Real Java

Write a generic `first` method and a copy method using bounds and wildcards, then verify compiler diagnostics for raw types and invalid assignments.

After This Lesson

java
import java.util.List;

class Main {
    static <T> T first(List<T> values) {
        if (values.isEmpty()) throw new IllegalArgumentException("empty list");
        return values.getFirst();
    }

    public static void main(String[] args) {
        String name = first(List.of("Ada", "Linus"));
        System.out.println(name);
    }
}
You should see
Ada

Try It Yourself

Write a generic `first` method and a copy method using bounds and wildcards, then verify compiler diagnostics for raw types and invalid assignments.

Common Mistake

Assuming `List<Integer>` is a subtype of `List<Number>` or hiding type problems with raw types.

Java Language Specification, Java SE 25Oracle

Easy traps

  • Assuming `List<Integer>` is a subtype of `List<Number>` or hiding type problems with raw types.
  • Assuming one sample output proves null, boundary, resource, and concurrency behavior are all correct.

Hands-on Exercise

Write a generic `first` method and a copy method using bounds and wildcards, then verify compiler diagnostics for raw types and invalid assignments.

You'll know it worked when: Ada