Java Generics 简明教程

Java Generics - Upper Bounded Wildcards

问号 (?) 代表通配符,在泛型中表示未知类型。有时,您可能希望限制可传递到类型参数的类型种类。例如,运算数字的方法可能只希望接受 Integer 实例或其超类,如 Number。

The question mark (?), represents the wildcard, stands for unknown type in generics. There may be times when you’ll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses.

要声明上限通配符参数,请按顺序列出 ? 及 extends 关键字,后跟其上限。

To declare a upper bounded Wildcard parameter, list the ?, followed by the extends keyword, followed by its upper bound.

Example

以下示例说明了如何使用 extends 指定上限通配符。

Following example illustrates how extends is used to specify an upper bound wildcard.

package com.tutorialspoint;

import java.util.Arrays;
import java.util.List;

public class GenericsTester {

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

   public static void main(String args[]) {
      List<Integer> integerList = Arrays.asList(1, 2, 3);
      System.out.println("sum = " + sum(integerList));

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

这会产生以下结果 −

This will produce the following result −

Output

sum = 6.0
sum = 7.0