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

Unbounded Wildcards

无界通配类型是通配符?的特殊用法。比如 List<?>,我们称之为list of unknown type(未知类型的列表)。在两种情况下,无界通配符能起很大作用:

  • 如果我们正在编写一个可以使用Object类中提供的功能来实现的函数

  • 在代码使用泛型类中不依赖于类型参数的函数。比如List.size或者List.clear,实际上Class<?>经常被用到,因为Class<T>中的大多数函数都不依赖于T

参考下面这个函数printList:

public static void printList(List<Object> list) {
    for (Object elem : list)
        System.out.println(elem + " ");
    System.out.println();
}

该函数的目的是以列表形式打印任何类型,但是该目标是无法实现的————它只能打印Object实例的列表,而不能打印List<Integer>, List<String>, List<Double>等等别的类型,因为它们不是List<Object>的子类型。使用List<?>编写通用的printList函数:

public static void printList(List<?> list) {
    for (Object elem: list)
        System.out.print(elem + " ");
    System.out.println();
}

对于任何具体类型A来说,List<A>是List<?>的子类型,所以我们可以用printList打印任何类型的列表:

List<Integer> li = Arrays.asList(1, 2, 3);
List<String>  ls = Arrays.asList("one", "two", "three");
printList(li);
printList(ls);
PreviousUpper Bounded WildcardsNextLower Bounded Wildcards

Last updated 5 years ago

Was this helpful?

在本课程的示例中,会使用函数。此静态工厂方法将指定的数组转换并返回固定大小的列表。

意识到List<Object>和List<?>是不一样的是很重要的。你可以往List<Object>中插入Object或者Object的子类型。但是你只能向List<?>中插入null。在部分中有更多关于如何确定在给定情况下应使用哪种通配符(如果有)的信息。

Arrays.asList
Guidelines for Wildcard Use