CodeGym /Courses /JAVA 25 SELF /Generics wildcards

Generics wildcards

JAVA 25 SELF
Level 27, Lesson 4
Available

1. Invariance of generics: List<Number> ≠ List<Integer>

In Java, generics are strict: they are invariant. This means that even if one type is a subtype of another (for example, Integer is a subtype of Number), collections with these types are unrelated.

Imagine: you have a box of apples (List<Integer>), and someone says it’s actually a “box of fruit” (List<Number>). Sounds reasonable—apples are fruit. But then someone could put a banana in the box (Double), and everything would break—the box is actually “apple-only.”

Code example:

List<Integer> intList = new ArrayList<>();
List<Number> numList = intList; // Compilation error!

The compiler is deliberately strict here: it doesn’t allow turning a list of “apples” into a list of “fruit.” Otherwise, we would be able to add anything to it, and the program would crash at runtime.

Therefore, List<Number> and List<Integer> are two completely different types, even though Integer itself is a subtype of Number.

Unlike arrays:

Integer[] intArr = new Integer[10];
Number[] numArr = intArr; // Allowed (arrays are covariant)
numArr[0] = 3.14; // Runtime error (ArrayStoreException)

Conclusion: generics are invariant to ensure type safety at compile time.

2. Type parameter bounds

Sometimes you need to restrict which types a generic class or method can work with. For this, you use bounds.

Upper bound (extends)

class Stats<T extends Number> {
    private T[] nums;
    // ...
}

Now Stats can work only with types that are subclasses of Number (Integer, Double, Float, etc.). Attempting to create Stats<String> will cause a compilation error.

Interface bound

class Sorter<T extends Comparable<T>> {
    void sort(List<T> list) { /* ... */ }
}

Now Sorter can work only with types that implement the Comparable interface.

Multiple bounds

You can specify several bounds at once using &:

class MyClass<T extends Number & Comparable<T>> { /* ... */ }

T must be a subclass of Number and implement Comparable<T>.

Order matters: class first, then interfaces.

3. Meet the wildcard: ?

A wildcard is a “placeholder” type that says: “There may be some type here, but I don’t know which one.”

Examples:

  • List<?> — a list of anything.
  • List<? extends Number> — a list of any type that is a subclass of Number (for example, Integer, Double).
  • List<? super Integer> — a list of any type that is an ancestor of Integer (for example, Integer, Number, Object).

Why do we need wildcards?

They let you write methods that work with collections of different but related types.

Example: read-only (producer)

void printNumbers(List<? extends Number> list) {
    for (Number n : list) {
        System.out.println(n);
    }
    // list.add(123); // Error! Cannot add elements
}
  • You can read elements as Number.
  • You cannot add elements (except null).

Example: write-only (consumer)

void addIntegers(List<? super Integer> list) {
    list.add(42); // OK
    // Integer x = list.get(0); // Error! We don't know which type will be returned
}
  • You can add elements of type Integer (or its subtypes).
  • You cannot safely read elements as Integer (only as Object).

PECS rule

PECS — “Producer Extends, Consumer Super”:

  • Producer — Extends: if a collection only produces data, use ? extends T.
  • Consumer — Super: if a collection only consumes data, use ? super T.

Easy to remember: extends — for reading (producer), super — for writing (consumer).

Comparison: arrays are covariant, generics are invariant

  • Arrays are covariant: Integer[] can be assigned to a variable of type Number[].
  • Generics are invariant: List<Integer> cannot be assigned to a variable of type List<Number>.

Wildcards let you partially “relax” the invariance of generics.

5. Generic methods and type inference; limitations (type erasure)

Generic methods

You can declare generic methods that work with arbitrary types:

public static <T> void printList(List<T> list) {
    for (T elem : list) {
        System.out.println(elem);
    }
}

Type inference

Java can “infer” the type parameter:

List<String> strings = List.of("a", "b");
printList(strings); // T = String

Generics limitations: type erasure

  • In Java, generics are implemented via type erasure: information about type parameters is removed after compilation.
  • In bytecode there is no difference between List<String> and List<Integer>.
  • You cannot create arrays of generic types: new List<String>[10] — error.
  • You cannot use instanceof with type parameters: obj instanceof List<String> — error.

6. Practice with collections and the Stream API

Copying elements between lists

public static <T> void copy(List<? super T> dest, List<? extends T> src) {
    for (T item : src) {
        dest.add(item);
    }
}
  • src — producer (? extends T)
  • dest — consumer (? super T)

Usage:

List<Integer> ints = List.of(1, 2, 3);
List<Number> nums = new ArrayList<>();
copy(nums, ints); // OK: Number is a supertype of Integer

Stream API and wildcards

List<Integer> ints = List.of(1, 2, 3);
List<? extends Number> numbers = ints;

numbers.stream()
    .map(Number::doubleValue)
    .forEach(System.out::println);

Printing with a wildcard

public static void printAll(List<?> list) {
    for (Object o : list) {
        System.out.println(o);
    }
}

7. Common mistakes

Error #1: Raw types.
Using raw types disables type checking and leads to runtime errors.

List list = new ArrayList(); // raw type — bad!
list.add("string");
list.add(123); // You can add anything

String s = (String) list.get(1); // ClassCastException!

Never use raw types. Always specify type parameters: List<String>, List<Integer>.

Error #2: Unsafe operations with extends.
Trying to add elements to a collection with ? extends ... will result in a compilation error.

List<? extends Number> nums = new ArrayList<Integer>();
nums.add(3.14); // Compilation error!

Error #3: Type erasure and overloading.
You cannot overload methods only by generic parameters—after type erasure the signatures are identical.

public void process(List<String> list) { /* ... */ }
public void process(List<Integer> list) { /* ... */ } // Compilation error!

Error #4: Arrays of generic types.
You cannot create arrays of parameterized types due to type erasure.

List<String>[] arr = new List<String>[10]; // Compilation error!
1
Task
JAVA 25 SELF, level 27, lesson 4
Locked
Calculating total asset value 💰
Calculating total asset value 💰
1
Task
JAVA 25 SELF, level 27, lesson 4
Locked
Universal Event Logging System 📜
Universal Event Logging System 📜
1
Survey/quiz
Collection interfaces, level 27, lesson 4
Unavailable
Collection interfaces
Collection interfaces
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION