Documentation

The Java™ Tutorials
Hide TOC
Unbounded Wildcards无界通配符
Trail: Learning the Java Language
Lesson: Generics (Updated)
Section: Wildcards

Unbounded Wildcards无界通配符

The unbounded wildcard type is specified using the wildcard character (?), for example, List<?>. 使用通配符(?)指定无界通配符类型,例如,List<?>This is called a list of unknown type. 这称为未知类型的列表There are two scenarios where an unbounded wildcard is a useful approach:有两种情况下,无界通配符是一种有用的方法:

Consider the following method, printList:考虑以下方法,PrimtList:

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

The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of Object instances; it cannot print List<Integer>, List<String>, List<Double>, and so on, because they are not subtypes of List<Object>. printList的目标是打印任何类型的列表,但它无法实现该目标—它只打印Object实例的列表;它无法打印List<Integer>List<String>List<Double>,等等,因为它们不是List<Object>的子类型。To write a generic printList method, use List<?>:要编写通用的printList方法,请使用List<?>

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

Because for any concrete type A, List<A> is a subtype of List<?>, you can use printList to print a list of any type:因为对于任何具体类型AList<A>都是List<?>的子类型,您可以使用printList打印任何类型的列表:

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

Note: The Arrays.asList method is used in examples throughout this lesson. 本课程的示例中使用了Arrays.asList方法。This static factory method converts the specified array and returns a fixed-size list. 此静态工厂方法转换指定的数组并返回固定大小的列表。

It's important to note that List<Object> and List<?> are not the same. 需要注意的是,该List<Object>List<?>不一样。You can insert an Object, or any subtype of Object, into a List<Object>. 你可以把一个ObjectObject的任意子类插入到List<Object>But you can only insert null into a List<?>. 但是null只能插入到List<?>The Guidelines for Wildcard Use section has more information on how to determine what kind of wildcard, if any, should be used in a given situation.通配符使用指南部分提供了有关如何确定在给定情况下应使用哪种通配符(如果有)的更多信息。


Previous page: Upper Bounded Wildcards
Next page: Lower Bounded Wildcards