Documentation

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

Lower Bounded Wildcards下界通配符

The Upper Bounded Wildcards section shows that an upper bounded wildcard restricts the unknown type to be a specific type or a subtype of that type and is represented using the extends keyword. 上界通配符部分显示上界通配符将未知类型限制为特定类型或该类型的子类型,并使用extends关键字表示。In a similar way, a lower bounded wildcard restricts the unknown type to be a specific type or a super type of that type.以类似的方式,下界通配符将未知类型限制为特定类型或该类型的超类型

A lower bounded wildcard is expressed using the wildcard character ('?'), following by the super keyword, followed by its lower bound: <? super A>.下限通配符使用通配符(?)表示,后跟super关键字,后跟其下限<? super A>


Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both. 可以指定通配符的上限,也可以指定下限,但不能同时指定两者。

Say you want to write a method that puts Integer objects into a list. 假设您想编写一个将Integer对象放入列表的方法。To maximize flexibility, you would like the method to work on List<Integer>, List<Number>, and List<Object> — anything that can hold Integer values.为了最大限度地提高灵活性,您希望该方法适用于List<Integer>List<Number>List<Object>—任何可以保存Integer值的东西。

To write the method that works on lists of Integer and the supertypes of Integer, such as Integer, Number, and Object, you would specify List<? super Integer>. 要编写适用于Integer列表和Integer超类型(如IntegerNumberObject)的方法,请指定List<? super Integer>The term List<Integer> is more restrictive than List<? super Integer> because the former matches a list of type Integer only, whereas the latter matches a list of any type that is a supertype of Integer.术语List<Integer>List<? super Integer>更具限制性,因为前者只匹配Integer类型的列表,而后者匹配Integer超类型的任何类型的列表。

The following code adds the numbers 1 through 10 to the end of a list:以下代码将数字1到10添加到列表的末尾:

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

The Guidelines for Wildcard Use section provides guidance on when to use upper bounded wildcards and when to use lower bounded wildcards.通配符使用指南部分提供了关于何时使用上限通配符和何时使用下限通配符的指导。


Previous page: Unbounded Wildcards
Next page: Wildcards and Subtyping