Documentation

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

Upper Bounded Wildcards上界通配符

You can use an upper bounded wildcard to relax the restrictions on a variable. 可以使用上界通配符来放宽对变量的限制。For example, say you want to write a method that works on List<Integer>, List<Double>, and List<Number>; you can achieve this by using an upper bounded wildcard.例如,假设您想编写一个在List<Integer>List<Double>List<Number>上起作用的方法;可以通过使用上界通配符来实现这一点。

To declare an upper-bounded wildcard, use the wildcard character ('?'), followed by the extends keyword, followed by its upper bound. 要声明上界通配符,请使用通配符(?),后跟extends关键字,再后跟其上界Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).注意,在此上下文中,extends在一般意义上表示“extends”(在类中)或“implements”(在接口中)。

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

Consider the following process method:考虑以下process方法:

public static void process(List<? extends Foo> list) { /* ... */ }

The upper bounded wildcard, <? extends Foo>, where Foo is any type, matches Foo and any subtype of Foo. 上界通配符<? extends Foo>,其中Foo是任意类型,匹配FooFoo的任何子类型。The process method can access the list elements as type Foo:process方法可以访问类型为Foo的列表元素:

public static void process(List<? extends Foo> list) {
    for (Foo elem : list) {
        // ...
    }
}

In the foreach clause, the elem variable iterates over each element in the list. foreach子句中,elem变量迭代列表中的每个元素。Any method defined in the Foo class can now be used on elem.Foo类中定义的任何方法现在都可以在elem上使用。

The sumOfList method returns the sum of the numbers in a list:sumOfList方法返回列表中数字的总和:

public static double sumOfList(List<? extends Number> list) {
    double s = 0.0;
    for (Number n : list)
        s += n.doubleValue();
    return s;
}

The following code, using a list of Integer objects, prints sum = 6.0:以下代码使用Integer对象列表打印sum = 6.0

List<Integer> li = Arrays.asList(1, 2, 3);
System.out.println("sum = " + sumOfList(li));

A list of Double values can use the same sumOfList method. Double列表可以使用相同的sumOfList方法。The following code prints sum = 7.0:以下代码打印sum = 7.0

List<Double> ld = Arrays.asList(1.2, 2.3, 3.5);
System.out.println("sum = " + sumOfList(ld));

Previous page: Wildcards
Next page: Unbounded Wildcards