Java Generics Wildcard Arguments

Introduction

To create a generic method to accept generic types, use the wildcard argument.

The wildcard argument is specified by the ?, and it represents an unknown type.

methodName(GenericType<?> ob){}
class MyArray<T extends Number> {   
  private T[] nums; // array of Number or subclass  
     //w  w  w . ja  va  2 s . c o m
  public MyArray(T[] o) {   
    nums = o;   
  }   
  public double average() {   
    double sum = 0.0;  
  
    for(int i=0; i < nums.length; i++)   
      sum += nums[i].doubleValue();  
  
    return sum / nums.length;  
  } 
  // wildcard 
  public boolean sameAvg(MyArray<?> 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 };  
    MyArray<Integer> iob = new MyArray<Integer>(inums);    
    double v = iob.average();  
    System.out.println("iob average is " + v);  
  
    Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };  
    MyArray<Double> dob = new MyArray<Double>(dnums);    
    double w = dob.average();  
    System.out.println("dob average is " + w);  
  
    Float fnums[] = { 1.0F, 2.0F, 3.0F, 4.0F, 5.0F };  
    MyArray<Float> fob = new MyArray<Float>(fnums);    
    double x = fob.average();  
    System.out.println("fob average is " + x);  
  
    // See which arrays have same average. 
    System.out.print("Averages of iob and dob "); 
    if(iob.sameAvg(dob)) 
      System.out.println("are the same.");  
    else 
      System.out.println("differ.");  
 
    System.out.print("Averages of iob and fob "); 
    if(iob.sameAvg(fob)) 
      System.out.println("are the same.");  
    else 
      System.out.println("differ.");  
  }   
}



PreviousNext

Related