Wildcard test program : Generic Method « Generics « Java Tutorial






import java.util.ArrayList;

public class MainClass {
  public static void main(String args[]) {
    Integer[] integers = { 1, 2, 3, 4, 5 };
    ArrayList<Integer> integerList = new ArrayList<Integer>();

    for (Integer element : integers)
      integerList.add(element);

    System.out.printf("integerList contains: %s\n", integerList);
    System.out.printf("Total of the elements in integerList: %.0f\n\n", sum(integerList));

    Double[] doubles = { 1.1, 3.3, 5.5 };
    ArrayList<Double> doubleList = new ArrayList<Double>();

    for (Double element : doubles)
      doubleList.add(element);

    System.out.printf("doubleList contains: %s\n", doubleList);
    System.out.printf("Total of the elements in doubleList: %.1f\n\n", sum(doubleList));

    Number[] numbers = { 1, 2.4, 3, 4.1 }; // Integers and Doubles
    ArrayList<Number> numberList = new ArrayList<Number>();

    for (Number element : numbers)
      numberList.add(element);

    System.out.printf("numberList contains: %s\n", numberList);
    System.out.printf("Total of the elements in numberList: %.1f\n", sum(numberList));
  }

  public static double sum(ArrayList<? extends Number> list) {
    double total = 0;

    for (Number element : list)
      total += element.doubleValue();

    return total;
  }
}
integerList contains: [1, 2, 3, 4, 5]
Total of the elements in integerList: 15

doubleList contains: [1.1, 3.3, 5.5]
Total of the elements in doubleList: 9.9

numberList contains: [1, 2.4, 3, 4.1]
Total of the elements in numberList: 10.5








12.3.Generic Method
12.3.1.Creating a Generic Method
12.3.2.Generic Constructors
12.3.3.Generic methods: Max. Min
12.3.4.Generic method maximum returns the largest of three objects
12.3.5.Using generic methods to print array of different types
12.3.6.Wildcard test program