Home > Java > javaTutorial > Java Generics: What's the Difference Between `? extends T` and `? super T` Wildcards?

Java Generics: What's the Difference Between `? extends T` and `? super T` Wildcards?

DDD
Release: 2024-12-10 06:11:17
Original
803 people have browsed it

Java Generics: What's the Difference Between `? extends T` and `? super T` Wildcards?

Java Generics: Exploring Wildcards

This article delves into the intricacies of generic wildcards in Java, addressing two fundamental questions:

  1. 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: 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: 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.
  1. Difference between and
  • List: 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: 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template