Java教程
  • Introduction
  • Getting Started
    • The Java Technology Phenomenon
      • About the Java Technology
      • What Can Java Technology Do?
      • How Will Java Technology Change My Life?
    • The Hello World Application
    • A Closer Look at the Hello World Application
  • Learning the Java Language
    • Object-Oriented Programming Concepts
      • What Is an Object?
      • What Is a Class?
      • What Is Inheritance?
      • What Is an Interface?
      • What Is a package?
    • Language Basics
      • Java Language Keywords
    • Annotations
      • Annotations Basics
      • Declaring an Annotation Type
      • Predefined Annotation Types
      • Repeating Annotations
      • Type Annotations and Pluggable Type Systems
    • Generics
      • Why Use Generics?
      • Generic Types
        • Raw Types
      • Generic Methods
      • Bounded Type Parameters
        • Generic Methods and Bounded Type Parameters
      • Generics, Inheritance, and Subtypes
      • Type Inference
      • Wildcards
        • Upper Bounded Wildcards
        • Unbounded Wildcards
        • Lower Bounded Wildcards
        • Wildcards and Subtyping
        • Wildcard Capture and Helper Methods
        • Guidelines for Wildcard Use
      • Type Erasure
        • Erasure of Generic Types
        • Erasure of Generic Methods
        • Effects of Type Erasure and Bridge Methods
        • Non-Reifiable Types
      • Restrictions on Generics
Powered by GitBook
On this page

Was this helpful?

  1. Learning the Java Language
  2. Generics
  3. Wildcards

Lower Bounded Wildcards

PreviousUnbounded WildcardsNextWildcards and Subtyping

Last updated 5 years ago

Was this helpful?

在部分中已经展示上界通配符如何通过extends关键字将未知类型限制成特定类型或该类型的子类型。同样的,lower bounded(下界)通配将未知类型限制成特定类型或该类型的super type(超类型)

一个下界通配表示如下:先写一个通配符?,后面紧跟super关键字,最后是它的下界:<? super A>

你不能同时指定通配的上界和下界,只能两者选其一

假设我们想写一个函数将Integer类型的对象添加到列表中,我们希望函数对List<Integer>, List<Number>, List<Object>(任何能持有Integer值的)都起作用

为了编写一个函数对于Integer及其超类型(比如Number和Object)的列表都能工作,我们可以指定List<? super Integer>。List<Integer>比List<? super Integer>的限制更大,因为它只接受Integer类型的列表,而后者接受任何Integer的超类型。

下面一段代码在列表尾部添加数字1到10:

public static void addNumbers(List<? super Integer> list) {
    for (int i = 1; i <= 10; i++) {
        list.add(i);
    }
}

部分介绍了何时使用上界通配或者下界通配。

Upper Bounded Wildcards
Guidelines for Wildcard Use