Java Generics Wildcards – Complete Guide with Examples
Learn how to use wildcards in Java Generics for flexible method parameters, including unbounded, upper-bounded, and lower-bounded wildcards with practical examples.
Wildcards in Java Generics – Complete Detailed Tutorial
Wildcards in Java Generics allow flexibility in specifying generic types, especially for method arguments, without losing type safety.
1. What are Wildcards?
- Represent an unknown type in generics
- Syntax:
<?> - Useful in methods and collections where type can vary
- Helps avoid code duplication
2. Types of Wildcards
2.1 Unbounded Wildcard <?>
- Represents any type
- Useful when you don’t care about the exact type
Example – Unbounded Wildcard
Output:
Key Points:
- Can read elements as Object
- Cannot add elements (except
null)
2.2 Upper-Bounded Wildcard <? extends Class>
- Represents subclasses of a specified class
- Allows reading elements safely
- Cannot add elements except
null
Example – Upper-Bounded Wildcard
Output:
Key Points:
- Read-only for method
- Ensures type safety for subclasses
2.3 Lower-Bounded Wildcard <? super Class>
- Represents superclasses of a specified class
- Useful when writing elements to a collection
- Cannot read elements as the specific type (can read as
Object)
Example – Lower-Bounded Wildcard
Output:
Key Points:
- Write-only for method
- Ensures type safety when adding subclasses
3. Summary Table of Wildcards
| WildcardMeaningCan ReadCan Write | |||
<?> | Any type | Yes (as Object) | No |
<? extends T> | T or subclass | Yes | No (except null) |
<? super T> | T or superclass | Limited (as Object) | Yes |
4. Key Points
- Wildcards increase flexibility of generics
- Upper-bound → use when reading
- Lower-bound → use when writing
- Unbounded → use when type doesn’t matter
- Avoid casting and duplication in generic methods