liveBook · Manning

Wildcard type

As explained in 100 Java Mistakes and How to Avoid Them

A wildcard type is a Java generic type argument represented by a question mark that permits constrained or unconstrained type variation.

A wildcard type uses ? as a Java generic argument to express an unknown type. The bounded form ? extends CharSequence accepts a List of one particular CharSequence subtype, such as String, while preventing ordinary additions through that reference. section 5.3.2

Accepting a more specific list safely

A method declared with List<CharSequence> cannot accept a List<String>: callers could add another CharSequence implementation. Declaring it as List<? extends CharSequence> accepts the String list while preserving the guarantee that the method will not add incompatible elements. section 5.3.2

Prefer these practices when a generic collection is consumed without modification:

  • Use a bounded wildcard in the method signature instead of upcasting and applying an unchecked cast. section 5.3.2
  • If a signature cannot change, pass an unmodifiable wrapper; its List<? extends T> parameter can adapt a more concrete list to a more abstract result. section 5.3.2
  • Treat unchecked generic casts as a last resort: type erasure can defer the resulting ClassCastException until a later use. section 5.5

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains wildcard bounds, write restrictions, library adaptation, unchecked casts, and delayed failures caused by type erasure.
Examples
Uses List<String>, List<CharSequence>, processList, unmodifiableList, and collection casts to demonstrate compatibility and failure modes.
What you can do after
Apply it via Java generics to replace unsafe casts with bounded parameters or read-only collection adapters.
How it connects
Connects wildcard types with Java generics, unchecked casts, type erasure, raw types, and ClassCastException.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.