ReviseAlgo Logo

Generics

Wildcards

Analyze wildcard parameters, upper/lower bounds, and the PECS design principle.

Interview: Focuses on PECS (Producer Extends, Consumer Super) usage, wildcards capture errors, and unbounded wildcard limits.

Last Updated: June 13, 2026 10 min read

Wildcards (represented by the question mark ?) are used as type arguments in method parameters to define flexible relationships between generic classes.

Upper Bounded

Declared using ? extends T. Restricts elements to type T or its subclasses, making the collection read-only.

Lower Bounded

Declared using ? super T. Restricts elements to type T or its superclasses, allowing elements to be added safely.

PECS Principle

"Producer Extends, Consumer Super": use extends when reading elements (producer), and super when writing elements (consumer).

PECS Rule and Wildcard Write Restrictions

The PECS principle defines how collections can be accessed:

  • Producer Extends: Use List<? extends Number> to read elements. Elements can be read as Number. However, you cannot add elements because the actual type is unknown at runtime.
  • Consumer Super: Use List<? super Integer> to write elements. You can safely add Integer objects. However, elements read from the list are returned as raw Object.

Common Pitfalls

  • Adding elements to an extends collection: Trying to call list.add(val) on a List<? extends Number>, which causes a compile-time error.
  • Assuming covariance: Believing a List<Number> reference can accept a List<Integer> object directly, which is prevented by Java's invariant generic rules.

Best Practices

  • Apply PECS to methods: Use wildcards on method arguments to make APIs flexible (e.g. public void pushAll(Iterable<? extends E> src)).
  • Avoid wildcards in return types: Do not use wildcards in method return types, as it forces callers to handle wildcard types.

Interview-Relevant Information

Q1: What does the PECS acronym stand for?
Answer: PECS stands for Producer Extends, Consumer Super. It is a guideline for designing API method signatures: use ? extends T when reading data from a collection, and ? super T when writing data into a collection.

Q2: Why can you not add elements to a List<? extends Number>?
Answer: The wildcard indicates the list holds elements of some unknown subtype of Number (e.g. Integer or Double). Because the compiler cannot verify the actual subtype at runtime, it blocks insertions to prevent type corruption.

Quick Checklist

Can you state the PECS rule, explain why extends collections are read-only, and describe why super collections can accept insertions? If yes, you understand wildcards.

Use Cases

Designing utility libraries that copy, merge, or transform lists of different types.

Building flexible data structures that accept subclass inputs.

Common Mistakes

Attempting to insert elements into an extends bounded collection.

Declaring wildcard types in method return signatures.