Generic Wildcard Arguments

To create a generic method, you use the wildcard argument. The wildcard argument is specified by the ?, and it represents an unknown type.

 
class Calculator<T extends Number> {
  T[] nums;
  Calculator(T[] o) {
    nums = o;
  }
  double average() {
    double sum = 0.0;
    for (int i = 0; i < nums.length; i++){
      sum += nums[i].doubleValue();
    }
    return sum / nums.length;
  }
}
public class Main {
  boolean sameAvg(Calculator<?> ob) {
    if (1.2 == ob.average())
      return true;
    return false;
  }

  public static void main(String args[]) {
  }
}
  

Calculator<?> matches any Stats object, allowing any two Stats objects to have their averages compared.

The following program demonstrates this:

 
class Calculator<T extends Number> {
  T[] nums;
  Calculator(T[] o) {
    nums = o;
  }
  double average() {
    double sum = 0.0;
    for (int i = 0; i < nums.length; i++)
      sum += nums[i].doubleValue();
    return sum / nums.length;
  }
  boolean sameAvg(Calculator<?> ob) {
    if (average() == ob.average())
      return true;
    return false;
  }
}
public class Main {
  public static void main(String args[]) {
    Integer inums[] = { 1, 2, 3, 4, 5 };
    Calculator<Integer> iob = new Calculator<Integer>(inums);

    Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
    Calculator<Double> dob = new Calculator<Double>(dnums);

    if (iob.sameAvg(dob))
      System.out.println("are the same.");
    else
      System.out.println("differ.");
  }
}
  
Home 
  Java Book 
    Language Basics  

Generics:
  1. Generic Class
  2. Generic Bounded Types
  3. Generic Wildcard Arguments
  4. Generic Bounded Wildcards
  5. Generic Method
  6. Generic Constructors
  7. Generic Interfaces
  8. Raw Types and Legacy Code
  9. Generic Class Hierarchies
  10. Run-Time Type Comparisons Within a Generic Hierarchy
  11. Overriding Methods in a Generic Class
  12. Generic Restrictions
  13. Generic Array Restrictions