Java Generics: Exploring Wildcards
This article delves into the intricacies of generic wildcards in Java, addressing two fundamental questions:
- Bounded vs. Unbounded Wildcards
Wildcards are represented with a question mark (?) followed by a bound. A bounded wildcard restricts the type of the generic, while an unbounded wildcard does not.
-
Bounded Wildcards:
- List extends T>: This indicates that the list can hold any subtype of T. It's an upper bound wildcard, meaning it restricts the type to extend T or any of its subclasses.
- List super T>: This indicates that the list can hold any supertype of T. It's a lower bound wildcard, meaning it restricts the type to be an ancestor of T or its parent classes.
- Difference between extends T> and super T>
- List extends T>: This type represents a list that can hold objects that are of type T or any subclass of T. For example, a list with elements of type Dog could be assigned to a list with this type parameter.
- List super T>: This type represents a list that can hold objects that are of type T or any superclass of T. For instance, a list with elements of type Animal could be assigned to a list with this type parameter.
Further Reading
For more comprehensive explanations of Java generics and wildcards, refer to the following resources:
- [Wildcards](https://docs.oracle.com/javase/tutorial/java/generics/wildcards.html)
- [More Fun with Wildcards](https://docs.oracle.com/javase/tutorial/extra/generics/morefunwithwildcards.html)
The above is the detailed content of Java Generics: What's the Difference Between `? extends T` and `? super T` Wildcards?. For more information, please follow other related articles on the PHP Chinese website!