Using Bounded Wildcards in Methods : Generic Parameters « Generics « Java Tutorial






The syntax for using an upper bound is as follows:

GenericType<? extends upperBoundType>
import java.util.ArrayList;
import java.util.List;

public class MainClass {
  public static double getAverage(List<? extends Number> numberList) {
    double total = 0.0;
    for (Number number : numberList) {
      total += number.doubleValue();
    }
    return total / numberList.size();
  }

  public static void main(String[] args) {
    List<Integer> integerList = new ArrayList<Integer>();
    integerList.add(3);
    integerList.add(30);
    integerList.add(300);
    System.out.println(getAverage(integerList)); // 111.0
    List<Double> doubleList = new ArrayList<Double>();
    doubleList.add(3.0);
    doubleList.add(33.0);
    System.out.println(getAverage(doubleList)); // 18.0
  }
}
111.0
18.0








12.4.Generic Parameters
12.4.1.Using the ? wildcard
12.4.2.Using Bounded Wildcards in Methods
12.4.3.Multiple Type Parameters
12.4.4.Type Parameter Bounds
12.4.5.Constraints on a Wildcard